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 ?

4

1 回答 1

2

如果您的想法是您将拥有一个将 JSON 数据打印到标准输出的 Python 脚本,那么您可能正在寻找popen.

就像是...

<?php

$f = popen('python /var/www/abc/abc.py', 'r');
if ($f === false)
{
   echo "popen failed";
   exit 1;
}
$json = fgets($f);
fclose($f);

...将输出抓取到$json变量中。

至于您的示例 Python 脚本,如果您的想法是您尝试将 Python 字典转换{"tests": "35"}为 JSON,并打印到标准输出,您需要更改loadsdumpsreturnto print,所以它看起来像......

import simplejson

def main():
    data = simplejson.dumps({"tests": "35"})
    print data

main()
于 2013-04-12T10:36:45.350 回答