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
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
To call a Python file from within a PHP file, you need to call it using the shell_exec function.
php $command_exec = escapeshellcmd('path-to-. py-file'); $str_output = shell_exec($command_exec); echo $str_output; ?> The right privileges need to be given so that the python script is successfully executed. Note − While working on a Unix type of platform, PHP code is executed as a web user.
Yes it will work, and how risky it is depends on how good your implementation is. This is perfectly acceptable if done correctly. I have successfully integrated PHP and C, when PHP was simply too slow to do certain niche tasks in real time (IIRC, PHP is 7 times slower than its C counterpart).
To execute Python function from JavaScript you can use Ajax to call a python script function from the server-side.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With