php to python inter-process communication with large data by json - php

my php code:
<?php
$data = array('as', 'df', 'gh');
$result=shell_exec("start test.py ".escapeshellarg(json_encode($data)));
?>
test.py code:
import sys
import json
try:
print json.loads(sys.argv[1])
except:
print "ERROR"
print
raw_input()
it's failing to try and showing ERROR.
while if change my python code to this:
import sys
try:
data=sys.argv[1]
except:
print "ERROR"
print data,
raw_input()
i'm getting the output as: [ as , df , gh ]
as i'm passing a json encoded data, i should be able to decode it with python's json.loads() method. but why it's not working?

don't know how it's working. but able to tune the program according to what i want.
php code:
<?php
$data = array('1'=>"as",'2'=>"df",'3'=>"gh");
$result=shell_exec("start test.py ".json_encode(json_encode($data)));
?>
test.py:
import sys
import json
try:
data=sys.argv[1]
except:
print "ERROR"
print data
dit=json.loads(data)
print dit
print dit['1']
raw_input()
and got the output as required:
{"1":"as","2":"df","3":"gh"}
{u'1': u'as', u'3': u'gh', u'2': u'df'}
as
someone having a good knowledge in these pls explain.

The problem is the following:
On Windows, escapeshellarg() removes percent signs, replaces double
quotes with spaces and adds double quotes around the string.
-> https://secure.php.net/manual/en/function.escapeshellarg.php
I'd recommend using addslashes(...)
exec("test.py " . addslashes(json_encode($json)) . " 2>&1", $output, $exit_code);

Related

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'])

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 . "'");
?>

get the inverse of a php matrix from python file

PHP code:
<?php
$arr=array(array('1','2','3','4'),array('21','12','23','54'),array('10','23','35','41'),array('14','62','93','40'));
$result = shell_exec("C:/Python27/python 123.py ".json_encode($arr));
echo $result;
?>
python code:
import sys, json
arr=sys.argv[1]
print arr
A=np.matrix(arr)
print A
print ("<br/>")
M=A.I
print M
result = {'Name':'abc'}
print ("Sending data to PHP")
print (json.dumps(result))
The output given as inverse is not coming correct plus the A matrix is coming out to be of dimenesion 1x16 instead of 4x4 and the dimension of array arr is correct(4x4).How to debug it and get correct matrices A and M?
You seem not to be decoding the JSON within the Python script, whilst json_encode($arr) should be json_decode($arr) unless I'm wrong.

I have to pass an array from a php file to python file but my code is giving output NULL

PHP code:
<?php
$data = array('1','4','67','34');
$result = shell_exec('C:/Python27/python C:/xampp/htdocs/123.py ' . escapeshellarg(json_encode($data)));
$resultData = json_decode($result, true);
var_dump($resultData);
?>
Python Code:
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 = {'23','4'}
# Send it to stdout (to PHP)
print json.dumps(result)
There is incorrect data for json.dump() in Python
# Generate some data to send to PHP
result = {'23','4'}
So this give error, not json string
import sys, json
# Generate some data to send to PHP
result = {'23','4'}
# Send it to stdout (to PHP)
print json.dumps(result)
and PHP get NULL as $result from Python so you get NULL on screen - in browser
Use (for example):
# Generate some data to send to PHP
result = {'a':'23','b':'4'}
and json.dump() will work fine.
Add 2>&1 (stdout & stderr) behind the command like so:
$result = shell_exec('C:/Python27/python C:/xampp/htdocs/123.py ' . escapeshellarg(json_encode($data)) . ' 2>&1');

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