大佬教程收集整理的这篇文章主要介绍了Windows上的Python子进程输出?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用的代码的基本版本:
import subprocess,time from threading import Thread def enqueue_output(out): print "Hello from enqueue_output" for line in iter(out.readline,''): line = line.rStrip("\r\n") print "Got %s" % line out.close() proc = subprocess.Popen("third_party.exe",stdout=subprocess.PIPE,bufsize=1) thread = Thread(target=enqueue_output,args=(proc.stdout,)) thread.daemon = True thread.start() time.sleep(30)
如果我将third_party.exe替换为此脚本,则此方法非常有效:
import time,sys while True: print "Test" sys.stdout.flush() time.sleep(1)
所以我不清楚魔法需要做什么才能使用原始命令.
这些都是subprocess.Popen行的所有变种我试过没有成功:
proc = subprocess.Popen("third_party.exe",bufsize=0) proc = subprocess.Popen("third_party.exe",sHell=TruE) proc = subprocess.Popen("third_party.exe",creationflags=subprocess.CREATE_NEW_CONSOLE) si = subprocess.STARTUPINFO() si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW proc = subprocess.Popen("third_party.exe",startupinfo=si)
编辑1:
在这种情况下,我实际上无法使用.communicate().我正在推出的应用程序仍然运行很长一段时间(几天到几周).我实际测试.communicate()的唯一方法就是在启动后立即杀死应用程序,我觉得不会给我有效的结果.
即使非线程版本也失败了:
import subprocess,time from threading import Thread proc = subprocess.Popen("third_party.exe",stderr=subprocess.PIPE) print "App started,reading output..." for line in iter(proc.stdout.readline,''): line = line.rStrip("\r\n") print "Got: %s" % line
编辑2:
感谢jdi,以下工作正常:
import tempfile,time,subprocess w = "test.txt" f = open("test.txt","a") p = subprocess.Popen("third_party.exe",sHell=True,stdout=f,stderr=subprocess.STDOUT,bufsize=0) time.sleep(30) with open("test.txt",'r') as r: for line in r: print line f.close()
proc = subprocess.Popen("third_party.exe",bufsize=1) print proc.communicate()
如果有效,那很好.然后你可能会遇到直接或可能在你的线程中读取stdout的问题.
如果这不起作用,你是否尝试过stderr到stdout?
proc = subprocess.Popen("third_party.exe",bufsize=1)
更新
既然你说communication()是死锁,那么你可以尝试另一种方法来看看它是否与子进程的内部缓冲区有问题…
import tempfile import subprocess w = tempfile.NamedTemporaryFile() p = subprocess.Popen('third_party.exe',stdout=w,bufsize=0) with open(w.name,'r') as r: for line in r: print line w.close()
以上是大佬教程为你收集整理的Windows上的Python子进程输出?全部内容,希望文章能够帮你解决Windows上的Python子进程输出?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。