Windows上的Python子进程输出?
发布时间:2020-12-14 02:00:49 所属栏目:Windows 来源:网络整理
导读:我在从子进程stdout管道获取输出时遇到了一些困难.我正在通过它启动一些第三方代码,以便提取日志输出.直到最近更新第三方代码,一切正常.更新后,python已无限期地开始阻塞,并且实际上没有显示任何输出.我可以手动启动第三方应用程序并查看输出. 我正在使用的
我在从子进程stdout管道获取输出时遇到了一些困难.我正在通过它启动一些第三方代码,以便提取日志输出.直到最近更新第三方代码,一切正常.更新后,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("rn") 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: 即使非线程版本也失败了: 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("rn") print "Got: %s" % line 编辑2: 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-server-2008 – 备份虚拟机
- windows-runtime – IOutputStream.FlushAsync的
- windows-server-2008 – 在Windows 2003 Active
- windows-server-2008 – 系统速度/内存考虑因素x
- windows – NTFS:用户可以编辑/删除没有权限的文
- 许可 – 使16位代码在WinXP或Vista中工作(或者如
- Desktop App Converter /提交到Windows应用商店
- Windows – 64位大型mallocs
- 如何在Windows 64上安装NumPy?
- 你能在一个Windows服务中托管多个WCF进程吗?
热点阅读