php - 从 PHP 调用 Python 并获取返回码

标签 php python

我正在从 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 中,您可以使用 exec 执行命令并获取返回码。

manual for exec 表示第三个参数是一个变量,其中将存储返回代码,例如

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

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

对于您所描述的返回代码,这似乎确实是一个合适的用途,即 0 表示成功,>0 是各种类型错误的代码。

关于php - 从 PHP 调用 Python 并获取返回码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2726551/

相关文章:

python - 通过比较Python中列表元素的值来比较列表

javascript - 如何通过ajax将php插入jquery追加?

python - 复制和修改 Dataframe Pandas

python - 将列索引字符串附加到 DataFrame 列

php - 转换mysql中的日期

python - python 中类之间传递属性的问题

python - 仅当第一行是其他下一行的子字符串时,如何对 DataFrame 行与另一行进行平均

java - 在 32 位系统上进行密码散列,然后迁移到 64 位系统

php - 拉维尔 4 : how do I check if a database entry already exists against my store function

javascript - 提交成功后显示alert或msgbox