欢迎访问宙启技术站
智能推送

Python中如何获取命令行输出结果

发布时间:2023-12-19 01:27:22

在Python中获取命令行输出结果可以使用subprocess模块。subprocess模块允许你创建子进程并与它进行交互。以下是一个获取命令行输出结果的示例:

import subprocess

# 执行命令,并获取输出结果
def get_output(command):
    result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    output = result.stdout.decode('utf-8').strip()
    if len(output) == 0:
        output = result.stderr.decode('utf-8').strip()
    return output

# 示例调用
output = get_output('ls')  # 调用命令行的ls命令,并获取输出结果
print(output)

在上述示例中,定义了一个get_output函数,该函数接受一个命令作为参数,并返回命令行输出结果。在函数内部,使用subprocess.run()来执行命令行命令,并将结果保存在result变量中。

然后,使用result.stdout.decode('utf-8').strip()来获取标准输出的字符串表示。如果标准输出为空,则使用result.stderr.decode('utf-8').strip()获取标准错误输出的字符串表示。

在示例中的调用中,使用ls命令获取当前目录的文件列表,并将输出结果打印出来。

除了使用subprocess.run()方法外,还可以使用subprocess.Popen()方法来执行命令行命令,并获取输出结果。以下是一个使用subprocess.Popen()方法的示例:

import subprocess

# 执行命令,并获取输出结果
def get_output(command):
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    output, error = process.communicate()
    output = output.decode('utf-8').strip()
    if len(output) == 0:
        output = error.decode('utf-8').strip()
    return output

# 示例调用
output = get_output('ls')  # 调用命令行的ls命令,并获取输出结果
print(output)

使用subprocess.Popen()方法,创建子进程后,使用process.communicate()方法来获取子进程的输出结果。在示例中的调用中,同样使用ls命令获取当前目录的文件列表,并将输出结果打印出来。

不管是使用subprocess.run()方法还是subprocess.Popen()方法,都可以获取命令行的输出结果,并在Python程序中进行处理。根据不同的需求,选择适合的方法来使用。