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

问题描述 投票:0回答:1

我正在尝试使用 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

我也尝试过:

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 运行时它似乎才会中断。

python subprocess wait
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
    可能不是变量名,而是字符串
  • 您混淆了两个变量名称,
    proc
    kprocess
  • 您盲目地解析
    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)
© www.soinside.com 2019 - 2024. All rights reserved.