【问题标题】:Subprocess wait() function doesn't seem to be waiting for the subprocess to complete子进程 wait() 函数似乎没有等待子进程完成
【发布时间】:2011-06-16 20:37:26
【问题描述】:

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


    【解决方案1】:

    您必须实际调用进程的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)
    

    【讨论】:

    • 感谢您的回答。对语法问题感到抱歉,我试图“解释”我的实际代码并混淆了。无论如何,问题似乎是test.php的一些路径问题,现在已经解决了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    相关资源
    最近更新 更多