phppythoninputpassthru

passing json string from php to python


I am trying to call a python script within a php script. However, I cannot seem to figure out how to pass an input through to the python script. The code I am using is as follows:

$input = '[{"item": "item1"}, {"item": "item2"}, {"item": "item3"}]';
$output = passthru("/usr/bin/python3.5 /path/python_script.py $input");

The output in python is a list that is created by splitting the string by spaces i.e. ' ' whilst removing the the quotation marks:

['/path/python_script.py', '[{item:', 'item1},', '{item:', 'item2},', '{item:', 'item3}]']

What would be the most straight-forward way to pass a json string through to python?


Solution

  • To resolve your problem, you need to pass the json as a string. In your PHP it's a string, but the moment you call passthru, it's converted to command line. So it calls python like this:

    /usr/bin/python3.5 /path/python_script.py [{"item": "item1"}, {"item": "item2"}, {"item": "item3"}]
    

    Python indeed splits it on space and sees each part as an argument. The solution would be to wrap it in a string for passthru if possible:

    $output = passthru("/usr/bin/python3.5 /path/python_script.py '$input'");
    

    Then in your python script you can use json.loads as described here.

    If you cannot wrap it in string, you could do this in yout python script to put it all together manually:

    ''.join(sys.argv[1:]) # leaving out the first index, filename.