php到python通过json实现大数据的进程间通信


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

我的php代码:

<?php
$data = array('as', 'df', 'gh');
$result=shell_exec("start test.py ".escapeshellarg(json_encode($data)));
?>

test.py代码:

import sys
import json
try:
    print json.loads(sys.argv[1])
except:
    print "ERROR"
print
raw_input()

尝试并显示ERROR失败。而如果将我的python代码更改为:

import sys
try:
    data=sys.argv[1]
except:
    print "ERROR"
print data,
raw_input()

我得到的输出是:[ as , df , gh ]

当我传递json编码的数据时,我应该能够使用python的json.loads()方法对其进行解码。但为什么它不起作用?

不知道它是如何工作的。但是能够根据我的需要调整节目。

php代码:

<?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()

并得到所需的输出:

{"1":"as","2":"df","3":"gh"}
{u'1': u'as', u'3': u'gh', u'2': u'df'}
as

有人在这些方面有很好的知识,请解释。

问题如下:

在Windows上,escapestellarg()删除百分号,替换double带空格的引号,并在字符串周围添加双引号。

->https://secure.php.net/manual/en/function.escapeshellarg.php

我建议使用addslashes(…)

exec("test.py " . addslashes(json_encode($json)) . " 2>&1", $output, $exit_code);