在Python中,可以使用subprocess模块来捕获子进程的日志输出。下面是一个示例代码:
import subprocess
def capture_subprocess_output(command):
    # 使用Popen创建子进程并捕获输出
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    # 读取标准输出和错误输出
    stdout, stderr = process.communicate()
    # 输出日志
    if stdout:
        print("标准输出:")
        print(stdout.decode())
    if stderr:
        print("错误输出:")
        print(stderr.decode())
# 示例调用
capture_subprocess_output("ls -l")
在上面的示例中,subprocess.Popen函数用于创建子进程,并通过stdout=subprocess.PIPE和stderr=subprocess.PIPE参数来捕获标准输出和错误输出。接下来,使用communicate()方法读取这些输出,并通过decode()方法将字节流转换为字符串。最后,根据需要输出标准输出和错误输出的日志。
请注意,Popen函数的shell参数设置为True,这允许我们在调用命令时使用shell语法。如果不需要使用shell语法,可以将shell参数设置为False。此外,还可以根据需要修改capture_subprocess_output函数的参数,以接受不同的命令作为输入。
                    上一篇:捕获字符串文本后的所有匹配模式