How to pass variables to PHP to Python function? - php

I have the code in PHP side:
function apiTest($arga){
if (!isset($arga['name'])) {
printf("Missing required parameter 'name'\n");
return RET_PARAMSMISSING;
}
$retVal = 'testing';
printf("JSON:\n%s",json_wrapper($retVal)
return RET_NOERROR;
}
case 'testing':
$retval = apiTest($arga);
break;
In Browser running this script locahost/testing.php. Here is printing correctly:
TIDBITS API
C:/wamp/www/testing.php running # Sat, 10 Dec 2016 14:08:06
Executing function 'Test'
JSON:
testing
RETURN: 0
Here is json_wrapper printing the output correctly.
This Json_wrapper value how to pass to python function.
I have tried using the below code, but it's not working.
def inventory(self, **kwargs):
return self.tidbitsapi('testing')
I need to get the PHP variable to python side and perform some operation and once pass to return value true/false to PHP.

Try using a system call:
from php:
system('C:/pythonXX/python.exe pathToPythonModule.py "' . arg . '"')
from python:
import sys
if __name__ == '__main__':
if len(sys.argv) > 2:
varFromPhp = sys.argv[2]
print(varFromPhp)
else: print("Didn't get parameter")

Related

Printing Python Variable to PHP page

I am trying to print a python variable to a php page. I have my php script status.php shown below
<?php
$result = json_decode(exec('python status.py'), true);
echo $result;
?>
This php page calls the status.py python page which is listed below
import json
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setuip(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
input_state = GPIO.input(23)
if input_state == False:
print("Door is closed")
D = 1
elif input_state == True:
print("Door is open")
D = 0
print json.dumps(D)
I can get the shell command to print the php variable which when the door is closed comes out to be
Door is closed
1
However I can't get the variable 1 to print to the php page when I run it from the browser. Any help would be greatly appreciated!
By changing
$result = json_decode(exec('python status.py'), true);
to
$result = json_decode(exec('sudo python status.py'), true); it enabled the variable to be passed from the python script to the php script. It seems there was an access problem when accessing the file via webrowser.

Passing variables from php to python and python to php

I am breaking my head to make this work but I am in a dead end. I have no idea what I am doing wrong.
I play with php and python; trying to execute a python script through php exec(), return an output and pass it to another python script.
This is my workflow:
1) Through jquery and an ajax request I pass some data to a php file (exec1.php) which looks like this:
$number = $_POST['numberOfClusters'];
$shape = $_POST['shapeFilePath'];
// EXECUTE THE PYTHON SCRIPT
$command = "python ./python/Module1.py $number $shape";
exec($command,$out,$ret);
print_r($out);
print_r($r); //return nicely 1.
2) The python file which I run Module1.py looks like this:
# this is a list of list of tuples
cls000 = [[(365325.342877, 4385460.998374), (365193.884409, 4385307.899807), (365433.717878, 4385148.9983749995)]]
# RETURN DATA TO PHP
print cls000
3) Then I have a nested AJAX request inside the success function of my previous AJAX request in which I pass the response (in this case the cls000 list) into a php script called (exec2.php) like this:
# PASS VARIABLES FROM FORM
$number = $_POST['numberOfClusters'];
$shape = $_POST['shapeFilePath'];
$clusterCoords = $_POST['response']; # response from previous Ajax request
// EXECUTE THE PYTHON SCRIPT
$command = "python ./python/Module2.py $number $shape $clusterCoords";
exec($command,$out,$ret);
print_r($out); ## THIS GIVES ME AN EMPTY ARRAY!!
print_r($ret); ## THIS GIVES ME A RETURN STATUS: 2
4) My Module2.py script looks like this:
number = int(sys.argv[1])
shape = sys.argv[2]
cls000 = json.loads(sys.argv[3])
# RETURN DATA TO PHP
print cls000
What am I doing wrong? If I remove this line 'cls000 = json.loads(sys.argv[9])' and return for example 'shape' everything works fine. But when I try to return cls000 I get a status code 2.
What am I missing here?

How to Correctly Run Python Script from PHP [duplicate]

This question already has answers here:
Running a Python script from PHP
(10 answers)
Closed 7 years ago.
I have a python script that I would like to run from PHP. This is my PHP script:
$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)));
// Decode the result
$resultData = json_decode($result, true);
// This will contain: array('status' => 'Yes!')
var_dump($resultData);
And this is my Python script:
import sys, json
# Load the data that PHP sent us
try:
data = json.loads(sys.argv[1])
except:
print "ERROR"
sys.exit(1)
# Generate some data to send to PHP
result = {'status': 'Yes!'}
# Send it to stdout (to PHP)
print json.dumps(result)
I would like to be able to exchange data between PHP and Python, but the above error gives the output:
ERROR NULL
Where am I going wrong ?
:::::EDIT::::::
I ran this:
$data = array('as', 'df', 'gh');
// Execute the python script with the JSON data
$temp = json_encode($data);
$result= shell_exec('C:\Python27\python.exe test.py ' . "'" . $temp . "'");
echo $result;
I am getting No JSON object could be decoded
On my machine, the code works perfectly fine and displays:
array(1) {
'status' =>
string(4) "Yes!"
}
On the other hand, you may make a few changes to diagnose the issue on your machine.
Check the default version of Python. You can do this by running python from the terminal. If you see something like:
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
you're fine. If you see that you are running Python 3, this could be an issue, since your Python script is written for Python 2. So:
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[...]
should be a clue.
Again from the terminal, run python myScript.py "[\"as\",\"df\",\"gh\"]". What do you see?
{"status": "Yes!"}
is cool. A different response indicates that the issue is probably with your Python script.
Check permissions. How do you run your PHP script? Do you have access to /path/to/? What about /path/to/myScript.php?
Replace your PHP code by:
<?php
echo file_get_contents("/path/to/myScript.php");
?>
Do you get the actual contents?
Now let's add a few debugging helpers in your PHP code. Since I imagine that you are not using a debugger, the simplest way is to print debug statements. This is OK for 10-LOC scripts, but if you need to deal with larger applications, invest your time in learning how to use PHP debuggers and how do use logging.
Here's the result:
/path/to/demo.php
<?php
$data = array('as', 'df', 'gh');
$pythonScript = "/path/to/myScript.py";
$cmd = array("python", $pythonScript, escapeshellarg(json_encode($data)));
$cmdText = implode(' ', $cmd);
echo "Running command: " . $cmdText . "\n";
$result = shell_exec($cmdText);
echo "Got the following result:\n";
echo $result;
$resultData = json_decode($result, true);
echo "The result was transformed into:\n";
var_dump($resultData);
?>
/path/to/myScript.py
import sys, json
try:
data = json.loads(sys.argv[1])
print json.dumps({'status': 'Yes!'})
except Exception as e:
print str(e)
Now run the script:
cd /path/to
php -f demo.php
This is what I get:
Running command: python /path/to/myScript.py '["as","df","gh"]'
Got the following result:
{"status": "Yes!"}
The result was transformed into:
array(1) {
'status' =>
string(4) "Yes!"
}
yours should be different and contain a hint about what is happening.
I got it to work by adding quotes around the argument!
Like so:
<?php
$data = array('as', 'df', 'gh');
$temp = json_encode($data);
echo shell_exec('python myScript.py ' . "'" . $temp . "'");
?>

Php Exec function

I am unable to understand why the return value in php is not working. Can anybody help me?
<?php
exec("xyz.py",$output,$return);
foreach($output as $item){
echo "$item";
}
echo $return;
?>
The script of xyz.py is as follows:
def func():
print ('Hello')
return 21
func()
The output is always Hello0 no matter what value xyz.py returns
Thanks in advance.
According to the PHP docs, the third argument of exec, ($return in your example), works like this:
If the return_var argument is present along with the output argument, then the return status of the executed command will be written to this variable
Since your python program ran fine, the return status should be 0 (no errors).
This might be what you want:
import sys
def func():
print ('Hello')
return 21
sys.exit(func())
Return parameter denotes the status of the exec() function and NOT what the program returns .
-1 = error
0 = success
Append this to your execution string, which allows you to capture any error output:
2>&1 &
So as per your example:
exec('xyz.py 2>&1 &', $output);
echo $output;

get value of a variable from a python script

I have a python script that returns a json object. Say, for example i run the following:
exec('python /var/www/abc/abc.py');
and it returns a json object, how can i assign the json object as a variable in a php script.
Example python script:
#!/usr/bin/python
import sys
def main():
data = {"Fail": 35}
sys.stdout.write(str(data))
main()
Example PHP script:
<?php
exec("python /home/amyth/Projects/test/variable.py", $output, $v);
echo($output);
?>
The above returns an empty Array. Why so ?
I want to call the above script from php using the exec method and want to use the json object returned by the python script. How can i achieve this ?
Update:
The above works if i use another shell command, For Example:
<?php
exec("ls", $output, $v);
echo($output);
?>
Anyone knows the reason ?
If the idea is you'll have a Python script which prints JSON data to standard out, then you're probably looking for popen.
Something like...
<?php
$f = popen('python /var/www/abc/abc.py', 'r');
if ($f === false)
{
echo "popen failed";
exit 1;
}
$json = fgets($f);
fclose($f);
...will grab the output into the $json variable.
As for your example Python script, if the idea is you're trying to convert the Python dictionary {"tests": "35"} to JSON, and print to standard out, you need to change loads to dumps and return to print, so it looks like...
import simplejson
def main():
data = simplejson.dumps({"tests": "35"})
print data
main()

Categories