简体   繁体   English

从 PHP 调用 Python 并获取返回码

[英]Call Python From PHP And Get Return Code

I am calling a python script from PHP.我正在从 PHP 调用 python 脚本。

The python program has to return some value according to the arguments passed to it. python 程序必须根据传递给它的参数返回一些值。

Here is a sample python program, which will give you a basic idea of what i am doing currently:这是一个示例 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

As you can see from the above code, my basic aim is从上面的代码可以看出,我的基本目标是

  1. for the python program to return some values (0,1,4,8 etc) depending on the arguments.让python程序根据参数返回一些值(0、1、4、8等)。
  2. And then the calling PHP program to access these returned values and do the appropriate operation.然后调用 PHP 程序访问这些返回值并执行相应的操作。

Currently i have used "sys.exit(n)", for that purpose.目前,我为此使用了“sys.exit(n)”。

Am i right in using sys.exit, or do I need to use something else?我使用 sys.exit 是否正确,还是需要使用其他东西?

And also what method exists in PHP so that I can access the return code from python?还有什么方法存在于 PHP 中,以便我可以从 python 访问返回代码?

Sorry for the long question, but hopefully it will help in you understanding my dilemma抱歉问了这么长的问题,但希望它能帮助你理解我的困境

Thanks a ton万分感谢

In PHP, you can execute a command and obtain the return code using exec .在 PHP 中,您可以执行命令并使用exec获取返回码。

The manual for exec says the third parameter is a variable in which the return code will be stored, for example exec手册说第三个参数是一个变量,其中将存储返回代码,例如

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

$ret_code will be the shell return code, and $output is an array of the lines of text printed to std. $ret_code将是 shell 返回码, $output是打印到 std 的文本行数组。 output.输出。

This does appear to be an appropriate use for a return code from what you described, ie 0 indicating success, and >0 being codes for various types of errors.这似乎是您描述的返回码的适当用法,即 0 表示成功,>0 是各种类型错误的代码。

That is correct use of exit().这是 exit() 的正确用法。 See also: http://docs.python.org/library/sys.html另见: http : //docs.python.org/library/sys.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM