【问题标题】:Call Python From PHP And Get Return Code从 PHP 调用 Python 并获取返回码
【发布时间】:2010-04-28 02:59:52
【问题描述】:

我正在从 PHP 调用 python 脚本。

python 程序必须根据传递给它的参数返回一些值。

这是一个示例 python 程序,它将让您对我目前正在做的事情有一个基本的了解:

#!/usr/bin/python
import sys

#get the arguments passed
argList = sys.argv

#Not enough arguments. Exit with a value of 1.
if len(argList) < 3:
    #Return with a value of 1.
    sys.exit(1)

arg1 = argList[1]
arg2 = argList[2]

#Check arguments. Exit with the appropriate value.
if len(arg1) > 255:
    #Exit with a value of 4.
    sys.exit(4)
if len(arg2) < 2:
    #Exit with a value of 8.
    sys.exit(8)

#Do further coding using the arguments------

#If program works successfully, exit with a value of 0

从上面的代码可以看出,我的基本目标是

  1. 让 python 程序根据参数返回一些值(0、1、4、8 等)。
  2. 然后调用 PHP 程序来访问这些返回值并执行相应的操作。

目前我为此使用了“sys.exit(n)”。

我是在使用 sys.exit,还是我需要使用其他东西?

PHP 中还有什么方法可以让我从 python 访问返回码?

抱歉这个问题太长了,但希望它能帮助你理解我的困境

非常感谢

【问题讨论】:

    标签: php python


    【解决方案1】:

    在 PHP 中,您可以使用exec 执行命令并获取返回码。

    execmanual 表示第三个参数是一个变量,例如将在其中存储返回码

    exec('python blibble.py', $output, $ret_code);
    

    $ret_code 将是 shell 返回码,$output 是打印到 std 的文本行数组。输出。

    这似乎是您所描述的返回代码的适当用途,即 0 表示成功,>0 是各种类型错误的代码。

    【讨论】:

    • 非常感谢 PHP function(exec) 获取返回值。但是,我还需要确认 sys.exit(n)。值 (n) 会返回到“$ret_code”吗?或者我应该使用另一种返回和退出python程序的方式?再次感谢
    • 只是,确认 sys.exit(n) 将值返回给 shell。在linux中,可以通过“echo $?”输出。在 Windows 中:“回显 %ERRORLEVEL%”。无法在“$ret_code”中确认它的值,但它解决了我的问题的 python 部分。再次感谢
    • 是的,sys.exit 值应该存储在 PHP exec 命令的返回码参数中。我不知道如何调用 Python,但我将它与 Java 和通过此方法调用的其他命令一起使用。
    【解决方案2】:

    这就是exit()的正确使用。另见:http://docs.python.org/library/sys.html

    【讨论】:

    • 请随意接受这个作为答案,然后单击检查。
    猜你喜欢
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 2014-03-01
    • 2013-10-24
    • 2015-10-06
    • 2011-05-06
    • 1970-01-01
    相关资源
    最近更新 更多