Python 使用communicate将子进程的stdout写入文件
我正在使用子流程运行一个可执行文件,并使用communicate将其输出管道化。最后,我将通信的内容写入一个文件。具体代码如下所示Python 使用communicate将子进程的stdout写入文件,python,subprocess,stdout,communicate,Python,Subprocess,Stdout,Communicate,我正在使用子流程运行一个可执行文件,并使用communicate将其输出管道化。最后,我将通信的内容写入一个文件。具体代码如下所示 run = subprocess.Popen(['executable'], stdout=subprocess.PIPE) output = run.communicate()[0] logfile = open('run.log', 'a') logfile.write(output) logfile.close() 在上述过程中,日志文件在运行结束时写入。但
run = subprocess.Popen(['executable'], stdout=subprocess.PIPE)
output = run.communicate()[0]
logfile = open('run.log', 'a')
logfile.write(output)
logfile.close()
在上述过程中,日志文件在运行结束时写入。但是,有没有办法在可执行文件运行时将输出写入日志?您的意思是:
with open("run.log","a") as f:
run = subprocess.Popen(['executable'], stdout=f)
我想我找到了解决这个问题的办法:
logfile = ('run.log', 'w')
run = subprocess.Popen(['executable'], stdout = logfile)
run.wait()
logfile.close()
第一行创建用于写入的
run.log
,stdout
在可执行文件运行时直接写入日志文件。run.wait()
等待可执行文件完成,然后关闭日志文件。使用子进程。选中\u call()
等待子进程完成(如问题中所述)check_call()
如果子流程返回非零退出状态,也会自动引发异常。谢谢@padraic。在上述工作的同时,终端从可执行文件中解放出来。有没有办法让子进程
在终端中保留可执行文件,直到运行结束?@Deepak:按照我的建议,只需将Popen
替换为check_call
。参数相同。由于Popen
在启动流程后返回,它是否会将与
块分开,导致f
作为一个关闭的文件保留?这在中有直接解释:stdin、stdout和stderr分别指定执行程序的标准输入、标准输出和标准错误文件句柄。有效值包括PIPE
、DEVNULL
、现有文件描述符(正整数)、现有文件对象和None