简体   繁体   English

从python脚本中获取变量的值

[英]get value of a variable from a python script

I have a python script that returns a json object. 我有一个返回json对象的python脚本。 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. 它返回一个json对象,如何将json对象指定为php脚本中的变量。

Example python script: 示例python脚本:

#!/usr/bin/python
import sys 

def main():
    data = {"Fail": 35}
    sys.stdout.write(str(data))

main()

Example PHP script: PHP脚本示例:

<?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. 我想使用exec方法从php调用上面的脚本,并希望使用python脚本返回的json对象。 How can i achieve this ? 我怎样才能实现这一目标?

Update: 更新:

The above works if i use another shell command, For Example: 如果我使用另一个shell命令,上面的工作原理,例如:

<?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 . 如果你的想法是你将有一个Python脚本将JSON数据打印到标准输出,那么你可能正在寻找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. ...将把输出抓取到$json变量中。

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... 至于你的示例Python脚本,如果你想要将Python字典{"tests": "35"}为JSON,并打印到标准输出,你需要将loads更改为dumpsreturn print ,看起来像......

import simplejson

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

main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM