从PHP调用Python并获取返回码 [英] Call Python From PHP And Get Return Code

查看:225
本文介绍了从PHP调用Python并获取返回码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从PHP调用python脚本.

I am calling a python script from 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:

#!/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. 让python程序根据参数返回一些值(0、1、4、8等).
  2. 然后调用PHP的程序访问这些返回的值并执行适当的操作.

目前,我为此目的使用了"sys.exit(n)".

Currently i have used "sys.exit(n)", for that purpose.

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

Am i right in using sys.exit, or do I need to use something else?

还有PHP中存在什么方法,以便我可以从python访问返回代码?

And also what method exists in PHP so that I can access the return code from python?

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

Sorry for the long question, but hopefully it will help in you understanding my dilemma

一吨

推荐答案

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

In PHP, you can execute a command and obtain the return code using exec.

exec手册说,第三个参数是返回代码将被存储,例如

The manual for exec says the third parameter is a variable in which the return code will be stored, for example

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

$ret_code是外壳程序返回代码,而$output是打印到std的文本行的数组.输出.

$ret_code will be the shell return code, and $output is an array of the lines of text printed to std. output.

这似乎确实适合您所描述的返回码,即0表示成功,而> 0是各种错误类型的代码.

This does appear to be an appropriate use for a return code from what you described, i.e. 0 indicating success, and >0 being codes for various types of errors.

这篇关于从PHP调用Python并获取返回码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆