Reputation: 21
I understand there are questions like mine already asked, but I can't figure this out even with the answers in those questions.
PHP:
<?php
$var1 = "hi";
$result = shell_exec('TestingStuff.py'.$var1);
?>
Python:
import sys
print(sys.argv[1])
Error received when running in Python:
IndexError: list index out of range
Both scripts are in the same folder.
Could someone please provide an answer with the code changes?
Upvotes: 0
Views: 1140
Reputation: 41756
Error
If the Python script runs with no arguments at all, then that sys.argv[1]
index is out of range.
Scripts
ExecPython.php
<?php
$var1 = "hi";
$result = shell_exec('TestingStuff.py ' . $var1);
echo "<pre>$result</pre>";
TestingStuff.py
import sys
if len(sys.argv) > 1:
print(sys.argv[1])
Demo
Explanation
We will start with the Python script. The goal is, that the script prints the first argument passed to it - without running into the "IndexError: list index out of range" error.
python TestingStuff.py 123
we want the output 123
.In Python the arguments passed to the script reside in sys.argv
. It's a list. sys.argv[0]
is always the script name itself (here TestingStuff.py
). Using the example from above sys.argv[1]
is now 123.
Handling the edge cases: "no argument" given.
python TestingStuff.py
This will result in an "IndexError: list index out of range" error, because you are trying to access a list element, which is not there. sys.argv[0]
is the script name and sys.argv[1]
is not set, but you are trying to print it and BAM goes the error. To avoid the error and only print the first argument, we need to make sure, that the list sys.argv
contains more than one element (more than the script name). That's why i've added if len(sys.argv) > 1:
.
That means: print the first argument only, if the list has more than 1 argument.
Now we can test the Python script standalone - with and without arguments. And switch over to the PHP script.
The goal is to execute the Python script from PHP.
PHP provides several ways to execute a script, there are for instance exec(), passthru(), shell_exec(), system(). Here we are using shell_exec(). shell_exec() returns the output of the script or command we run with it.
In other words: if you run $result = shell_exec('php -v');
, you'll get the PHP version lines in $result.
Here we are executing the Python script TestingStuff.py
and add an argument, which is $var1
. It's a string and added via concatenation to the string given to shell_exec(). The $result
is echoed. I wrapped pre-tags around it, because i thought this is executed in the web/browser context. If you are using the scripts only on the CLI, you might drop the pre-tags.
Execution flow
$result
Upvotes: 2