Get and save the console output of the process started by subprocess.
You can save the console output of test.exe to a text file with the following code. Both test.bat (and .bat file) can save console output to a text file.
** Use subprocess.Popen (.., stdout = .., stderr = ..), send console output to this process with stderr = subprocess.PIPE, and start withproc.communicate () Wait for the end of the process. (If there is no proc.communicate (), it will continue without waiting for the end, and it will be parallel processing) **
trial.py
# -*- coding: utf-8 -*-
#To get / save the console output of the process started by subprocess
# ref: https://www.it-swarm-ja.tech/ja/python/subprocesscall%EF%BC%88%EF%BC%89%E3%81%AE%E5%87%BA%E5%8A%9B%E3%82%92%E5%8F%96%E5%BE%97%E3%81%99%E3%82%8B/968744582/
import subprocess
def main(): #For execution switching
run__main1()
# sec:Get and save console output
def run__main1():
#result:
# test.exe console output can be saved
# test.bat can also save console output,.bat is also possible
# case: FAIL
# subprocess.call("test.exe > res.log.txt")
# case: Popen(.., stdout=..)use
with open("res.log.txt", 'w') as file_log:
proc = subprocess.Popen(
["test.bat"],
stdout=file_log, stderr=subprocess.PIPE)
proc.communicate() #Required for standby, if output is required: stdout, stderr = proc.communicate()
print("return code:", proc.returncode) # DEBUG:For standby / end confirmation
# case: end
print("ended.")
# sec: entry
if __name__ == "__main__": main()
https://www.it-swarm-ja.tech/ja/python/subprocesscall%EF%BC%88%EF%BC%89%E3%81%AE%E5%87%BA%E5%8A%9B%E3%82%92%E5%8F%96%E5%BE%97%E3%81%99%E3%82%8B/968744582/
Recommended Posts