【问题标题】:Read output from a Python command in a PHP webapp在 PHP webapp 中读取 Python 命令的输出
【发布时间】:2014-12-05 11:20:36
【问题描述】:

我正在尝试从 php webapp 读取 python 输出。

我在 php 代码中使用 $out = shell_exec("./mytest") 来启动应用程序,并在 python 应用程序中使用 sys.exit("returnvalue") 来返回值。

问题是$out 不包含我的返回值。 相反,如果我尝试使用$out = shell_exec("ls"),$out 变量包含ls 命令的输出。

如果我从终端运行./mytest,它可以工作,我可以在终端上看到输出。

【问题讨论】:

    标签: php python shell-exec


    【解决方案1】:
    sys.exit("returnvalue")
    

    使用带有sys.exit 的字符串用于指示错误值。所以这将在stderr 中显示returnvalue,而不是stdout。 shell_exec() 默认只捕获stdout。

    您可能希望在 Python 代码中使用它:

    print("returnvalue")
    sys.exit(0)
    

    或者,您也可以在 PHP 代码中使用它来将 stderr 重定向到 stdout。

    $out = shell_exec("./mytest 2>&1");
    

    (事实上,both 可能是最好的,因为如果发生意外情况,让 stderr 消失可能会很混乱)。

    【讨论】:

    • print("returnvalue") sys.exit(0) 不起作用...$out = shell_exec("./mytest 2>&1") 有效,但它只返回最后一行,不幸的是,panda3d 在我的返回值之后添加了 2 行消息...
    • @stafanovinci 我不知道你的 Python 代码,或者你的 PHP 代码。我无法指出我不知道的代码中的任何错误;-)。这是您发布的代码中的错误...
    猜你喜欢
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    相关资源
    最近更新 更多