要捕获Python中的shell命令输出并在自己的脚本中使用,可以使用subprocess
模块。下面是一个示例代码:
import subprocess
# 执行shell命令,并将输出捕获到变量中
output = subprocess.check_output("ls", shell=True)
# 打印命令输出
print(output.decode())
# 或者直接使用subprocess.Popen获取输出
process = subprocess.Popen("ls", stdout=subprocess.PIPE, shell=True)
output, error = process.communicate()
print(output.decode())
在上面的示例中,subprocess.check_output
函数用于执行shell命令并将输出捕获到变量output
中。shell=True
参数表示要使用shell来执行命令。
另一种方法是使用subprocess.Popen
函数。它返回一个表示执行命令的进程对象。stdout=subprocess.PIPE
参数用于将命令输出重定向到管道,然后可以使用communicate
方法获取输出和错误信息。
在两种方法中,输出结果都是一个字节字符串,需要使用decode
方法将其转换为普通字符串。
下一篇:捕获Python函数的输出