python如何获取exe软件输出的log日志

exe文件也是用python写的,拿pyinstaller转成了exe。这个exe会在结束的时候输出warning级别的日志。比如logger.warning("hello world")输出“hello world”。那么我如何在主线程调用这个exe子程序的时候,获取到这个“hello world”呢?

取决于你用什么库调用,也取决于除了 warning 有没有其他信息

举个例子,假设你使用suprocess,Python >= 3.3.4,程序的唯一输出就是你要的信息

import subprocess

message_string = subprocess.getoutput('your_exe.exe')

或者使用 Popen,可以设置 stderr 为 PIPE,之后就可以当成普通流/文件对象使用了

# warning 信息为 strerr,而不是 stdout
proc = suprocess.Popen(['your_exe.exe'], stderr=subprocess.PIPE)

message_bytes = proc.stderr.read()

或者可以使用 Popen.communicate()

proc = suprocess.Popen(['your_exe.exe'], stderr=subprocess.PIPE)

#proc.communicate() 返回 tuple: (stdout_bytes, stderr_bytes)
message_bytes = proc.communicate()[1]