子进程wait()函数似乎没有等待子进程完成

问题描述:

我试图用python的子进程模块运行php脚本。子进程wait()函数似乎没有等待子进程完成

proc = subprocess.Popen(['php', '-f', test.php], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 

retCode = proc.wait 

print retCode 

val = float(kprocess.stdout.read()) 

return val 

我也试过:

proc = subprocess.Popen(['php', '-f', test.php], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 

val = float(kprocess.communicate()[0]) 

return val 

两种方式都在本地工作时,我只要运行它在Python解释器,但是当我尝试实际的服务器上运行它,我总是得到“ float()的/空字符串处的ValueError“。这使我相信这个过程不知何故被等待。我错过了什么?

编辑:我使用的是Django,所以它只在我用Django运行时似乎中断。

你有实际调用进程的wait功能:

proc = subprocess.Popen(...) 
retCode = proc.wait # retCode will be the function wait 
retCode = proc.wait() # retCode will be the return code 

不过,既然你都将输出重定向到,你应该注意在wait文档的警告,并使用communicate代替。确保你的代码是免费的语法错误:

  • test.php可能不是一个变量名,而是一个字符串
  • 你混淆了两个变量名,prockprocess
  • 你盲目地解析的communicate结果(这不是严格意义上的错误,但会阻碍错误检测和跟踪)

相反,我建议:

proc = subprocess.Popen(['php', '-f', 'test.php'], 
         stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
stdout,stderr = proc.communicate() 
if proc.returncode != 0: 
    raise Exception('Test error: ' + stderr) 
return float(stdout) 
+0

感谢您的回答。对于语法问题抱歉,我试图“解释”我的实际代码并混淆了。无论如何,这个问题似乎是test.php的一些路径问题,现在已经解决了。谢谢! – anonymous 2011-06-16 23:48:42