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

-1 python subprocess wait communicate

我正在尝试使用python的子进程模块运行php脚本.

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
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

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

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

return val
Run Code Online (Sandbox Code Playgroud)

当我在python解释器中运行它时,两种方式都在本地工作,但是当我尝试在实际服务器上运行它时,我总是得到"ValueError at/empty string for float()".这让我相信这个过程在某种程度上没有被等待.我错过了什么?

编辑:我正在使用Django,所以当我使用Django运行时它似乎只会破坏.

phi*_*hag 5

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

proc = subprocess.Popen(...)
retCode = proc.wait # retCode will be the function wait
retCode = proc.wait() # retCode will be the return code
Run Code Online (Sandbox Code Playgroud)

但是,由于您要将输出重定向到,因此您应该注意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)
Run Code Online (Sandbox Code Playgroud)