1

I want to run a script with python3 version 3.6.1 out of php by using

 $data = escapeshellarg($data);
 $resultpy = shell_exec("/usr/local/bin/python3 path/to/myscript.py 2>&1 $data");

$data json object contains floating point numbers on which I want to do some computations in python. I did set up a local bin for python3 following Gordon Davisson's suggestion Cannot create a symlink inside of /usr/bin even as sudo because python3 does not appear in /usr/bin/ after installation on Mac OS X 10.9.5. I have done the same for python2 to check if this would work in principle. When using

$resultpy = shell_exec("/usr/local/bin/python2 path/to/myscript.py 2>&1 $data"); 

, I can run the python script and get the expected output, but not when using

$resultpy = shell_exec("/usr/local/bin/python3 path/to/myscript.py 2>&1 $data"); 

I also can successfully call both python3 and python2 in shell using /usr/local/bin/python3 or /usr/local/bin/python2, respectively.

Could there be something wrong with the python script itself (maybe some syntax change in python3 compared to python2)?

from collections import OrderedDict
import sys, json
import scipy
import scipy.cluster.hierarchy as sch

try:
 data = json.loads(sys.argv[1], object_pairs_hook=OrderedDict) 

except (ValueError, TypeError, IndexError, KeyError) as e:
 print json.dumps({'error': str(e)})
 sys.exit(1)

print json.dumps(data)

I also added a she-bang line at the top of the python script but this did not solve it as expected. All import modules are installed in both versions. Any help with this is much appreciated!

schustischuster
  • 743
  • 9
  • 29

1 Answers1

3

If you want this to work in python3 you'll need to change the lines with print

from collections import OrderedDict
import sys, json
import scipy
import scipy.cluster.hierarchy as sch

try:
  data = json.loads(sys.argv[1], object_pairs_hook=OrderedDict) 

except (ValueError, TypeError, IndexError, KeyError) as e:
print( json.dumps({'error': str(e)}) )
sys.exit(1)

print( json.dumps(data) )
tink
  • 14,342
  • 4
  • 46
  • 50