Python子进程显示在终端上登录并保存在文件中

问题描述 投票:1回答:1

我正在使用子进程运行Python脚本,并愿意将输出保存到文件以及在终端上显示实时日志。 我已将下面的代码及其保存日志写入文件,但未在终端上显示实时脚本执行日志。

TCID = sys.argv[1]

    if TCID == "5_2_5_3":
        output = subprocess.check_output([sys.executable, './script.py'])
        with open('scriptout.log', 'wb') as outfile:
            outfile.write(output)
python python-3.x logging subprocess
1个回答
0
投票

我认为这将解决您的问题

import subprocess

outputfile = open('scriptout.log', 'a')
process = subprocess.Popen(["ping", "127.0.0.1"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
    output = process.stdout.readline()
    if output == b'' and process.poll() is not None:
        break
    if output:
        out = output.decode()
        outputfile.write(out)
        print(out, end="")

outputfile.close()

我也试过了

import subprocess

output = subprocess.check_output(["ping", "127.0.0.1"])
with open('scriptout.log', 'wb') as outfile:
    print(output)
    outfile.write(output)

但它在命令执行结束后输出。另外我想尝试使用记录模块,但我不知道如何使用它抱歉:(

© www.soinside.com 2019 - 2024. All rights reserved.