Parse PHP data to python script - php

this is my first time coding on python, i have a nested array that i want to parse it to python where the json will be process there and return the data back to php. But since this is my first time coding on python i have no idea how to parse json data from php to python vice versa. all i know is how to run python script from php using exec().
PHP
$alternative_val = array(
array('1','0.5','3'),
array('2','1','4'),
array('0.333','0.25','1')
);
$json_alter = json_encode($alternative_val);
$output = shell_exec('python test.py');
echo $output;
after python receive the json data from php i should go into a list,
expected python result
X = [['1','0.5','3'],['2','1','4'],['0.333','0,25','1']]
print(X)

You can use json_encode function for your php script and modify your shell command with arguments. And after that you will get your json data in py script.
PHP:
$alternative_val = array(
array('1','0.5','3'),
array('2','1','4'),
array('0.333','0.25','1')
);
$json_alter = json_encode($alternative_val);
$output = shell_exec('python test.py "' . $json_alter . '"');
echo $output;
PYTHON:
import sys
x = sys.argv[1]
print(x)

Related

php passthru returns no output

I am trying to call a python script from php. However, I cannot figure out how to return the result to my php script in order to use it there. My php script is as follows:
<?php
$input = 'help';
$output = passthru("/usr/bin/python3.5 /path/test.py '$input'");
echo $output;
?>
whilst my python script 'test.py' is:
import sys
json2 = sys.argv[1]
That's because your python script returns nothing. Just doing:
json2 = sys.argv[1]
Only assigns the value to json2. I suspect you're trying to do something like:
import sys
json2 = sys.argv[1]
print json2
That seems to work just fine:
~ # php -a
Interactive shell
php > $input = 'help';
php > $output = passthru("/usr/bin/python test.py '$input'");
help
Update:
Based on your comment. You're looking for exec() instead:
~ # php -a
Interactive shell
php > $input = 'help';
php > $output = exec("/usr/bin/python test.py '$input'");
php > echo $output;
help
Note that your Python script has to output something. Just assigning a variable is not going to work, since PHP cannot interpret your Python code for you. It can only run the script and do something with the script's output.

Unable to call a python script through PHP

I Have been stuck for a couple of days now. I am attempting to call a simple python script from PHP. For the life of me I cannot figure out what the issue is. I have made the onoff.py script executable with chmod +x.
I can run the script just fine from the command line like this:
pi#raspberrypi:/var/www/html $ python onoff.py
LED on
LED off
My issue is when I try to call the script from PHP. I get nothing.
My Python Script:
#!/usr/bin/python
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
print "LED on"
GPIO.output(18,GPIO.HIGH)
time.sleep(1)
print "LED off"
GPIO.output(18,GPIO.LOW)
My PHP Script:
<?php
$command = escapeshellcmd('python /var/www/html/onoff.py');
$output = shell_exec($command);
echo $output;
?>
Any help is greatly appreciated!
EDIT:
if I change my onoff.py script to a simple while loop such as:
#!/usr/bin/python
x=1
while (x<10):
print x
x=x+1
the output on the browser is:
1 2 3 4 5 6 7 8 9
I just don't understand why the loop will run but I get no output with the original python code.
EDIT 2:
Ok So I taking a different approach and trying to see where the code fails. I am adding bits of code at a time. Please see the following.
#!/usr/bin/python
import random
import time
import RPi.GPIO as GPIO
randomNumber = random.randint(1, 20)
GPIO.setmode(GPIO.BCM)
#GPIO.setup(18,GPIO.OUT)
print randomNumber
Now when I run the PHP it shows a random number so I know the python script is running. When I un-comment GPIO.setup(18,GPIO.OUT) and run the php I get a blank screen. I have no idea why this would make the script fail.
shell_exec() will only return a string if $command a). Ran OK and assuming b). that it spits its response to STDOUT.
Use exec() and pass it your command, an integer $code and an empty array $response both of which are treated by PHP as arguments by reference.
Run your command thus:
$command = escapeshellcmd('/path/to/python /var/www/html/onoff.py');
$response = array();
$code = 0;
exec($command, $response, $code);
var_dump($code, $response);
die;
You should now see what is actually being given to PHP internally and why the Python script isn't working.
You need to use python before the script, i.e.:
$command = escapeshellcmd('python /var/www/html/onoff.py');
If it doesn't work, python probably ins't on the PATH of the apache user and you may need to use the full path to the python binary, use which to find the full path:
which python
//usr/bin/python
The use that value:
$command = escapeshellcmd('/usr/bin/python /var/www/html/onoff.py');
Note:
Make sure apache user has execute permissions on onoff.py

How to properly call Python 3 script from PHP?

I would like to call a Python 3 script (with arguments) from PHP and process the returned information.
//server.php
arg1 = $_POST['arg1'];
arg2 = $_POST['arg2'];
args = array(arg1,arg2);
//pseudo code - THIS IS WHERE MY QUESTION IS
//$results = call_python3_script_somehow
echo $results
#script.py
import MyProcess
#take in args somehow
args = [arg1,arg2]
result = MyProcess(args)
return result
The problem is this has been asked many times on Stack Overflow, and there are different answers each one:
The execute function (here and here)
$output = array();
exec("python hi.py", $output);
var_dump( $output);
The escape shell function (here)
$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;
The shell execute function (here)
// This is the data you want to pass to Python
$data = array('as', 'df', 'gh');
// Execute the python script with the JSON data
$result = shell_exec('python /path/to/myScript.py ' . escapeshellarg(json_encode($data)));
The system function (here)
$mystring = system('python myscript.py myargs', $retval);
All of these answers are accepted and have a decent number of upvotes. Which, if any of these, is the proper way to call a Python script from PHP?
They all do the same thing but have some different output. I would suggest to use the one that best fits your scenario.
I often use shell_exec because it's easier for me on debugging since I all I need to do is just print a string out in <pre> tags. There's one thing that people tend to forget, especially when they are trying to debug stuff. Use: 2>&1 at the end of the script and the args. Taking one of the examples you have above, it would look something like this:
shell_exec('python /path/to/myScript.py ' . escapeshellarg(json_encode($data)) . " 2>&1");
This allows you to view error output as well, which is more than likely what you'll need to figure out why it's working on the command line, but it's not working when you run it from PHP.

Passing PHP variable into a Python script not working

I am trying to call a simple python script from a php script. The result I am getting is just a single word while my actual input is a long text/sentence. The php script should return the entire sentence; it currently outputs only "The"
Python script
import sys
print sys.argv[1]
Php script
$var1 = "The extra sleep will help your body wash out stress hormones.";
$output = exec("C:\Python27\python.exe example.py $var1");
echo $output;
Because command line parameters are space-delimited, you have to add some quotes:
$output = exec("C:\Python27\python.exe example.py \"$var1\"");
Your Python script is printing the first parameter that it receives. That first parameter is "The".

How to get response from python to php?

Php never get response If I use sleep for 5 minutes or more in python. Using sleep around 2 minutes , its working, I do not know what is happening, where is the problem?
Sample Code
uploadfile_database.php:
<?php
$file_id=1;
$response=exec('python /home/xyz/test.py '.$file_id);
echo $response;
?>
test.py
import os, json
import sys
sleep(300)
#sleep(420)
print "hello"
exec does not work as you're expecting. To get the output from of your python script you need to pass an output parameter to exec.
Ex.
$output = array();
$exit_code = exec('python /home/xyz/test.py '.$file_id, &$output);
You could also just use shell_exec which would work as you're expecting

Categories