Subprocess的wait()函数似乎未等待子进程完成

-1 投票
1 回答
4342 浏览
提问于 2025-04-16 19:44

我正在尝试用Python的subprocess模块来运行一个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

我也试过:

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

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

return val

这两种方法在我本地用Python解释器直接运行时都能正常工作,但当我在实际服务器上运行时,总是出现“ValueError at / empty string for float()”的错误。这让我觉得进程好像没有被正确等待。我漏掉了什么呢?

补充:我在使用Django,所以只有在用Django运行时才会出问题。

1 个回答

5

你需要实际调用进程的 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)

撰写回答