Reputation: 1
How to pass data from PHP to Python? This is my code. PHP:
$data = 'hello';
$result = shell_exec('/home/pi/Python.py' .$data);
Python:
result = sys.argv[1]
print(result)
But when run python code it show error:
"IndexError: list index out of range"
.
don't know Why?
Is it have other code for pass data from PHP to python?
Upvotes: 0
Views: 7677
Reputation: 1
I am creating a machine-learning web application using PHP and here is how I send my data from PHP to Python file. So, I have created a simple PHP and Python file and sent data accordingly.
test.php
<?php
echo shell_exec("py test.py 1 2 3 ");`
?>
py: is the location of your python.exe. You can either use py or python depending on your operating system. test.py: is the location of your python file. if both PHP and Python are in the same folder, you can write the name of the Python file here. 1 2 3: is the array of data you want to send to the Python file.
test.py
import sys
num_1 = sys.argv[1]
num_2 = sys.argv[2]
num_3 = sys.argv[3]
total = int(num_1)+int(num_2)+int(num_3)
print(total)
Hope it helps 😣
Upvotes: 0
Reputation: 105
Provide space between command and argument:
try the following snippet
php : test.php
<?php
$data = 'hello';
$output=shell_exec("python test.py " .$data);
echo $output;
?>
python : test.py
import sys
result = sys.argv[1]
print(result+" by python!")
Upvotes: 3
Reputation: 906
You should add space after script name
$data = 'hello';
$result = shell_exec('/home/pi/Python.py ' .$data);
Upvotes: 0