0

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 ?

6
  • 1
    Does the Python script output an object in JSON notation? If so, it's simply json_decode(exec(...)). If not, make it output :) Commented Apr 12, 2013 at 10:31
  • 2
    You'd need to print the JSON data, not return it.. Commented Apr 12, 2013 at 10:31
  • @MartijnPieters: Even if I print it returns an empty Array. Check updated question. Commented Apr 12, 2013 at 12:43
  • Your code works fine for me. Commented Apr 12, 2013 at 14:35
  • you mean using it with ls. Yeah it works for me as well for any system commands but as soon as i switch to running any custom python scripts it returns an empty Array Commented Apr 15, 2013 at 5:11

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

5 Comments

for this i need to print the data instead of returning, right ?
still doesn't work. It says $json is a Boolean type object.
Updated answer, but it means that the popen() failed, so either python isn't in your path, it can't find /var/www/abc/abc.py or there's an error in your Python script.
It actually had to do with permissions.
Ah. That would also explain it. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.