简体   繁体   中英

Python subprocess display logs on terminal and save in file

I am running a Python script using subprocess and willing to save output to a file as well as show live logs on terminal.
I have written below code and its saving logs in file but not showing live script execution logs on terminal.

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)

I think this will fix your issue

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()

also I tried

import subprocess

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

but it outputs after command execution ends. Also I want try with logging module but I don't know how to use it sorry :(

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM