I have written a web app that calls python code in places to retrieve and store information. It worked fine until today when I had reason to install the jsonpickle library. The library does precisely what's expected when the python code is run from shell (it converts nested structures to JSON; the data in this case is too complex for json.dumps(), which I would otherwise use). But when called from php, it fails to load. I've never seen this with any other library.
Extremely simplified code below:
Python:
#!/usr/bin/env python
import datetime
import jsonpickle
nowS = datetime.datetime.now().strftime("%m/%d/%Y, %H:%M:%S")
nowJ = jsonpickle.encode({"now": nowS})
print(nowJ)
The above works just fine whether I have it print nowS
or nowJ
.
However when the same code it called from PHP, it fails.
<!DOCTYPE html>
<html>
<body>
<?php
$json = shell_exec('python3 /var/www/py/trivial.py');
$json = trim($json);
echo "<p>json: " . addslashes($json) . "</p>";
?>
</body>
</html>
It can be made to work if I print nowS
and comment out all references to jsonpickle
. The line import jsonpickle
prevents PHP from being able execute this code even if jsonpickle is never later invoked.
The datetime and other libraries, installed earlier, cause no similar problem.
I'm confounded. What am I missing here?
CodePudding user response:
Since you have the shebang line at beginning of the file, you can simply call the file as an executable without Python3
. That python3 may be a different one from /usr/bin/env python
and so it may not be able to find the newly installed package jsonpickle
.
In short you can just do
shell_exec('/var/www/py/trivial.py');
Though, you have to make sure the script is executable for the PHP user.
CodePudding user response:
It must use full path. Like this:
shell_exec('/usr/bin/python3 /var/www/py/trivial.py');
Or try to create a venv (virtual environment) and install all required packages.
shell_exec('/var/www/py/venv/bin/python3 /var/www/py/trivial.py');
FYI: If you use apache to host your php, you also need to check the user (such as www-data) permissions.