12

I am calling a python script from PHP.

The python program has to return some value according to the arguments passed to it.

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. for the python program to return some values (0,1,4,8 etc) depending on the arguments.
  2. And then the calling PHP program to access these returned values and do the appropriate operation.

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

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

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

Thanks a ton

seaboy
  • 153
  • 1
  • 1
  • 8

2 Answers2

15

In PHP, you can execute a command and obtain the return code using 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 will be the shell return code, and $output is an array of the lines of text printed to std. output.

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.

jesterjunk
  • 2,342
  • 22
  • 18
JAL
  • 21,295
  • 1
  • 48
  • 66
  • Thanks a lot for PHP function(exec) to get the return values. But, I also need confirmation on sys.exit(n). Will the value (n) be returned to "$ret_code"? Or should I use another way of returning and exiting the python program? Thanks again – seaboy Apr 28 '10 at 03:35
  • Just, confirmed that sys.exit(n) returns the value to the shell. In linux, it can be outputted by "echo $?". While in Windows : "echo %ERRORLEVEL%". Could not confirm its value in "$ret_code", but it solved the python part of my problem. Thanks again – seaboy Apr 28 '10 at 05:37
  • Yes, the sys.exit value should be stored in the return code param by the PHP exec command. I don't know about calling Python, but I use it for this with Java and other commands I invoke through this method. – JAL Apr 28 '10 at 16:18
0

That is correct use of exit(). See also: http://docs.python.org/library/sys.html

Jake
  • 2,515
  • 5
  • 26
  • 41