在Python中,可以使用subprocess
模块来捕获正在运行的进程的标准输出。下面是一个示例代码:
import subprocess
# 定义要执行的命令
command = 'ls'
# 使用subprocess.Popen启动进程并捕获标准输出
process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
# 循环读取标准输出
while True:
# 逐行读取标准输出
output = process.stdout.readline()
if output == b'' and process.poll() is not None:
break
if output:
print(output.decode().strip())
# 等待进程结束
process.wait()
在上述示例中,我们使用subprocess.Popen
启动一个进程,并将标准输出通过stdout=subprocess.PIPE
参数捕获。然后使用process.stdout.readline()
逐行读取标准输出,并使用decode()
方法将字节转换为字符串进行处理。最后,使用process.wait()
等待进程结束。
需要注意的是,subprocess.Popen
的shell
参数设置为True
,表示使用shell来执行命令。如果不需要使用shell,可以将shell
参数设置为False
。
另外,如果需要捕获标准错误输出,可以使用stderr=subprocess.PIPE
参数,类似地进行处理。