2017-10-21 128 views
0

我很难在python中解析数组时来自php文件。从PHP发送数组到Python,然后在Python中解析

test.php的

$count = 3; 
    $before_json = array("qwe","wer","ert"); 
    print_r($before_json); 

    $after_json = json_encode($before_json); 
    echo $after_json; 

    $command = escapeshellcmd("test.py $after_json $count"); 
    $output = shell_exec($command); 
    echo $output; 

的print_r($ before_json);将显示 - Array([0] => qwe [1] => wer [2] => ert)

echo $ after_json;将显示 - [ “QWE”, “WER”, “ERT”]

py.test

import sys 
    after_json = sys.argv[1] 
    count = sys.argv[2] 
    print (device_id) 

打印(after_json)将打印 - [QWE,疫情周报,ERT]

打印( after_json [1])将打印 - q

如何打印出after_json中的任何3个项目?

+3

你忘了解析Python中的json。导入'json'模块,然后您可以使用'json.loads(after_json)'将JSON字符串转换为列表。 **更新**:我觉得这应该是一个答案,而不是一个评论,但我会留下评论,因为它已经有一些upvotes。 – rickdenhaan

+0

首先让python程序执行你期望的操作 - 你只是读取一个字符串并从字符串中输出第一个字符......并尝试使用临时文件或管道在程序之间发送数据,而不是命令行 – MatsLindh

回答

0

你仍然需要解析Python中的JSON字符串。您可以使用json模块为:

import sys, json 
after_json = sys.argv[1] 
count = sys.argv[2] 

parsed_data = json.loads(after_json) 
print (parsed_data[0]) # will print "qwe" 
0

你所看到的问题是缺乏在Python JSON解析,如经rickdenhaan说。

但是你也需要确保正确引用您的字符串,当你在这条线将其发送到shell解释:

$command = escapeshellcmd("test.py $after_json $count"); 

如果我们手工填写的变量,我们会得到下面的结果(不知道什么是$count,所以我只是假设值为3):

$command = escapeshellcmd("test.py [\"qwe\",\"wer\",\"ert\"] 3"); 

这只适用,因为在你的JSON格式没有空格。只要分析过的JSON中有空格,Python脚本的shell调用就会完全失败。这也是一个安全噩梦,因为JSON数组的每个元素都可能导致shell中的任意代码执行。

当你将它们传递给shell时,你必须逃避你的论点。为此,您应该使用功能escapeshellarg

这可能是你想做的事,而不是什么:

$escaped_json = escapeshellarg($after_json) 
$command = escapeshellcmd("test.py $escaped_json $count"); 

如果你不是100%肯定$count是一个整数,你也应该调用escapeshellarg上的参数。

+0

谢谢大家。我做了你的改变,但我得到一个空白输出。 $ count只是一个计数器,我将在py脚本中循环使用。测试。php是 $ count = 3; $ before_json = array(“qwe”,“wer”,“ert”); $ after_json = json_encode($ before_json); $ escaped_json = escapeshellarg($ after_json); \t $ command = escapeshellcmd(“python test.py $ escaped_json $ count”); $ output = shell_exec($ command); echo $ output; 和test.py是 进口SYS,JSON escaped_json = sys.argv中[1] 计数= sys.argv中[2] parsed_data = json.loads(escaped_json) 打印(parsed_data [0]) – Gino

+0

也注意到在执行parsed_data = json.loads(escaped_json)之后做一个简单的打印“测试”将不会打印 – Gino

+0

如果我打印带有test.py的escaped_json,我得到这个\ [\“qwe \”,\“wer \ “,\”ert \“\] – Gino