【问题标题】:Python subprocess display logs on terminal and save in filePython子进程在终端上显示日志并保存在文件中
【发布时间】:2018-06-06 17:34:41
【问题描述】:

我正在使用子进程运行 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】:

我认为这将解决您的问题

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)

但它在命令执行结束后输出。我也想尝试使用日志模块,但我不知道如何使用它对不起:(

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    相关资源
    最近更新 更多