get value of a variable from a python script - php

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()

Related

How to capture return value from JAR in PHP and display it

I have following JAVA program which has been converted to JAR file and placed in the same directory as my PHP file.
So basically it takes an argument passed by PHP and displays it
public class Test {
public static void main(String[] args) throws Exception {
//Takes the value passed from the PHP
String Name = (new String(args[0])).toString();
//This will be treated as Output Parameter which will be returned to PHP
System.out.println("Return to PHP");
}
}
Below is my PHP code which will execute the JAR file and pass the required 1 parameter to the JAR.
<?php
$arg1 = "My_INPUT_PARAMETER";
shell_exec("java -jar TEST.jar $arg1");
echo "Done";
?>
I read somewhere that what ever the placed in Sysout (System.out.println) will be treated as output parameter or Return value to PHP.
So in my case it will be String "Return to PHP".
But I am not able to get the value to PHP and display it.
I tried placing a output value in the exec statement but its not working.
I tried below code but its throwing me error.
<?php
$arg1 = "My_INPUT_PARAMETER";
$output = '';
shell_exec("java -jar TEST.jar $arg1", $output);
echo "Done";
echo $output;
?>
Can anyone help me out here, How can I get a return value from PHP or output parameter from PHP and display it or use it in my PHP and continue with other execution part.
Thanks #Roland Starke.
So basically we can use 2 statements to run the JAR file from PHP:
EXEC and SHELL_EXEC.
EXEC will hold all the return values from JAR file and we can use it as Array and Display the required output parameter.
SHELL_EXEC will hold all the output parameters and it will display all at once.
<?php
$arg1 = "Multi Return";
exec("java -jar TEST.jar $arg1",$output);
echo $output[0]."<br/>";
echo $output[1];
echo "-------------------------------";
$shell_out = shell_exec("java -jar TEST.jar $arg1");
echo $shell_out;
?>

Pass JSON Data from PHP to Python Script

I'd like to be able to pass a PHP array to a Python script, which will utilize the data to perform some tasks. I wanted to try to execute my the Python script from PHP using shell_exec() and pass the JSON data to it (which I'm completely new to).
$foods = array("pizza", "french fries");
$result = shell_exec('python ./input.py ' . escapeshellarg(json_encode($foods)));
echo $result;
The "escapeshellarg(json_encode($foods)))" function seems to hand off my array as the following to the Python script (I get this value if I 'echo' the function:
'["pizza","french fries"]'
Then inside the Python script:
import sys, json
data = json.loads(sys.argv[1])
foods = json.dumps(data)
print(foods)
This prints out the following to the browser:
["pizza", "french fries"]
This is a plain old string, not a list. My question is, how can I best treat this data like a list, or some kind of data structure which I can iterate through with the "," as a delimiter? I don't really want to output the text to the browser, I just want to be able to break down the list into pieces and insert them into a text file on the filesystem.
Had the same problem
Let me show you what I did
PHP :
base64_encode(json_encode($bodyData))
then
json_decode(shell_exec('python ' . base64_encode(json_encode($bodyData)) );
and in Python I have
import base64
and
content = json.loads(base64.b64decode(sys.argv[1]))
as Em L already mentioned :)
It works for me
Cheers!
You can base64 foods to string, then passed to the data to Python and decode it.For example:
import sys, base64
if len(sys.argv) > 1:
data = base64.b64decode(sys.argv[1])
foods = data.split(',')
print(foods)
If you have the json string: data = '["pizza","french fries"]' and json.loads(data) isn't working (which it should), then you can use: MyPythonList = eval(data). eval takes a string and converts it to a python object
Was having problems passing json from PHP to Python, my problem was with escaping the json string, which you are doing. But looks like you were decoding then re-encoding with "food"
From what I understand
Python json.dumps(data) == PHP json_encode(data)
Python json.loads(data) == PHP json_decode(data)
json.loads(data) -> String Data
json.load(data) -> File Data
json.dumps(data) -> String Data
json.dump(data) -> File Data
PHP:
$foods = array("pizza", "french fries");
$result = shell_exec('python ./input.py ' . escapeshellarg(json_encode($foods)));
echo $result;
Python:
data = json.loads(sys.argv[1])
for v in data:
print(v)
ALSO
if you are passing key:value
PHP:
$foods = array("food1":"pizza", "food2":""french fries");
$result = shell_exec('python ./input.py ' . escapeshellarg(json_encode($foods)));
echo $result;
Python:
data = json.loads(sys.argv[1])
for(k,v) in content2.items():
print("k+" => "+v)
Python:
data = json.loads(sys.argv[1])
print(data['food1'])

Does python json output values have maximum length for json_decode (php) to handle?

I am trying to write a php code that takes coefficients from a html form, sends them to a python algorithm that returns a json object. That object is a list of player names, basically {"Ji" : "Firstname Lastname"} for i from 1 to 15.
The python code (interface.py) I have to create this json is :
import json
i=0
for joueur in best_team:
i+=1
output["J%s"%(i)]=joueur['nom']
out=json.dumps(output)
print(out)
best_team is a list of player dictionnaries with data on them. My player names don't involve any non ASCII characters or whatever.
My php code is the following :
$command = "python interface.py";
$command .= " $coeff1 $coeff2 $coeff3 $coeff4 $coeff5 $coeff6 $coeff7 $coeff8 $coeff9 $coeff10 2>&1";
$pid = popen( $command,"r");
while( !feof( $pid ) )
{
$data = fread($pid, 256);
$data= json_decode($data) ;
echo $data->J1;
flush();
ob_flush();
echo "<script>window.scrollTo(0,99999);</script>";
usleep(100000);
}
pclose($pid);
I call the coefficients from the html and then send back the results via a js file.
But I just get the following error : Notice: Trying to get property of non-object.
Nothing wrong with the js file because if I try instead :
$string = '{"foo": "bar", "cool": "attributlong"}';
$result = json_decode($string);
echo $result ->cool;
It works.
Also if I have instead in my python file :
out={"foo":"bar","word":"longerthaneightcharacters"}
out=json.dumps(out)
print(out)
It works as well (replacing J1 by word in php code of course).
And funny enough, if i have in python:
output={}
i=0
for joueur in best_team:
i+=1
output["J%s"%(i)]="short"
output["J%s"%(i)]=str(output["J%s"%(i)])
out=json.dumps(output)
print(out)
It works, and if I replace "short" by "longerthaneightcharacters" it doesn't work anymore.
So basically my question is, why is there a maximum number of characters in my output loop and how can I bypass it ? Thanks, I am very confused.

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?

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;

Categories