Python 子进程的奇怪IO行为

Python 子进程的奇怪IO行为,python,subprocess,stdout,Python,Subprocess,Stdout,我注意到python中的这种奇怪行为——我试图记录一个进程的输出,然后读取这个输出并对其进行一些处理。即使在程序运行后打开该文件时,该文件包含所有文本,但我无法读取任何内容 简单到 f=open("blah.txt",'w') #I log the output of a program with subprocess Cmdline="program.exe" Dump= subprocess.Popen(CmdLine,stdout=f,stderr=subprocess.STDOUT) #

我注意到python中的这种奇怪行为——我试图记录一个进程的输出,然后读取这个输出并对其进行一些处理。即使在程序运行后打开该文件时,该文件包含所有文本,但我无法读取任何内容

简单到

f=open("blah.txt",'w')
#I log the output of a program with subprocess
Cmdline="program.exe"
Dump= subprocess.Popen(CmdLine,stdout=f,stderr=subprocess.STDOUT)
#Waiting for it to finish
while(Dump.poll() is not None): #returns None while subprocess is running
        print "waiting on process to finish \n"
f.flush() #I flush everything to make sure it was written
sys.stdout.flush()
f.close()
#now i need to read from this file

f= open("blah.txt", 'r')
line=f.readline()
while line:
    print line
    line=f.readline()

f.close()

我什么也没读,但当我在运行程序后打开blah.txt文件时,一切都在那里。有没有关于我可能做错了什么的提示?我没有从“等待进程完成”中得到任何打印,但进程运行大约需要一秒钟。

代码中的错误是这一部分

while(Dump.poll()不是None):#while Dump.pool不是None保持循环运行

应该是

while(Dump.poll()为None):#while Dump.pool为None时保持循环运行

在while循环中,只要
Dump.poll()
不是一个循环,就基本上保持循环运行。问题是
Dump.pool()
在进程完成之前不会返回任何值。这意味着while循环将在您捕获进程的任何输出之前立即取消

这是您的代码的更新版本,我已确认其工作正常

with open("blah.txt",'w') as w:
    #I log the output of a program with subprocess
    Cmdline="program.exe"
    Dump = subprocess.Popen(CmdLine,stdout=w,stderr=subprocess.STDOUT)
    #Waiting for it to finish
    while(Dump.poll() is None): #returns None while subprocess is running
        print "waiting on process to finish \n"
    w.flush() #I flush everything to make sure it was written
    sys.stdout.flush()

#now i need to read from this file
with open("blah.txt", 'r') as f:
    line=f.readline()
    while line:
        print line
        line=f.readline()

我还建议您使用关键字来确保文件在完成任务后始终正确关闭

等待转储过程完成:

Dump= subprocess.Popen(CmdLine,stdout=f,stderr=subprocess.STDOUT)
#Waiting for it to finish
Dump.wait() # or -> while(Dump.poll() is None): print...

发生的情况是,由于等待循环是错误的,因此在轮询之前不给进程一个要启动的更改,因此它甚至不会在关闭/打开文件之前等待它启动:

什么是
f
?它不应该是
f=open吗(…
?抱歉,输入错误。已修复。这不是我的程序中的问题。@Illusionist有许多地方很明显这不是你正在运行的程序。请发布一个尽可能少的修改-否则,错误可能在其他地方。例如,在我的系统上工作正常。最小化你的应用程序,但使其更安全确定它仍然会重现问题。发布它。你几乎不想像那样循环
poll
。如果你想阻止,直到它完成,只需调用
wait
。如果你确实因为某种原因必须忙着等待,至少每次循环都要
sleep
,而不是试图消耗尽可能多的CPU时间没什么。+1很好,但除非我误解了他,否则他提到该文件确实包含了所有预期的文本,它只是没有显示在第二部分。是的,但它在执行读取打开位后被填充。顺便说一句,他的代码的问题是输入错误。while循环应该是
是None
,而不是
不是None
.a-statement在套件完成后自动关闭文件,因此
w.close()
f.close()
不可用necessary@ferkulat啊,在粘贴代码时忘了编辑它。;)