my php code:

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

test.py code:

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

it's failing to try and showing ERROR. while if change my python code to this:

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

i'm getting the output as: [ as , df , gh ]

as i'm passing a json encoded data, i should be able to decode it with python's json.loads() method. but why it's not working?

有帮助吗?

解决方案

don't know how it's working. but able to tune the program according to what i want.

php code:

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

and got the output as required:

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

someone having a good knowledge in these pls explain.

其他提示

The problem is the following:

On Windows, escapeshellarg() removes percent signs, replaces double quotes with spaces and adds double quotes around the string.

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

I'd recommend using addslashes(...)

exec("test.py " . addslashes(json_encode($json)) . " 2>&1", $output, $exit_code);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top