Python package not imported when executed through PHP - php

I'm getting a import error for spacy when executing new_api.py through PHP. The python script gets successfully executed when run through the cmd
PHP Code
<?php
$json = file_get_contents('php://input');
$input = json_decode($json, TRUE);
$result = shell_exec('/usr/bin/python3 new_api.py "'.$input['queryResult']['queryText'].'" "'.$input['session'].'" 2>&1');
$output = json_encode(array(
"source" => "source",
"fulfillmentText" => $result
));
print_r($output);
?>
Snippet Of Python Code
import requests
import json
import sqlite3
import spacy
import sys
json_values = sys.argv[1:]
result = (home(json_values[0],json_values[1]))
print(result)
The Output/Error Traceback
{"source":"source","fulfillmentText":"Traceback (most recent call last):\n File \"new_api.py\", line 4, in \n import spacy\nImportError: No module named 'spacy'\n"}
There's two version of python in the server. Both the versions has spacy installed in it and the python script is compatible with both versions.
Things I've tried
Tried using exec() and shell_exec() in php
Tried using which python path to execute the script
Tried running the script which both python and python3
The ImportError Still persists even after trying the combinations of the above steps. Any help would be appreciated.

Probably the user of the server who execute the PHP script does not have enough permissions to access the module.
You can install the module as server user or use venv

I have same problem, and I soleved it just a moment ago. This question is old, but I leave a note for people has same problem, and for me.
"printenv" on shell (your own user).
exec('printenv') from php (probably "apache" user).
Check difference between 1 and 2 results.
In my case, LD_LIBRARY_PATH=/usr/local/pgsql/lib is needed (exist in 1 and not exist in 2). So I modified my code as follows:
exec('LD_LIBRARY_PATH=/usr/local/pgsql/lib python3 test_script.py 2>&1');

Related

Laravel + Apache executing Python script with matplotlib

I am using php 7 with laravel 5.4 and I'm trying to execute some python scripts that use matplotlib to create some plots.
Use-case:
Python script script.py:
print("DONE")
Command line outputs:
d:\workspace>python sample.py
DONE
Creating a small php file test.php:
<?php
exec('sample.py', $output);
print_r($output);
?>
will output:
d:\workspace>php test.php
Array
(
[0] => DONE
)
Doing the same thing from a laravel controller method:
public function show_with_file($id, $file)
{
...
// Execute python script to retrieve dot-plot
$command = escapeshellcmd('d:\\workspace\\sample.py');
exec($command, $output);
dd($output);
...
}
will dump the output:
array:1 [▼
0 => "DONE"
]
Everything is running ok until now. But, if we modify the python script to include the matplotlib module:
import matplotlib
print("DONE")
executing the script will be successful, executing the test.php file in command line works fine, but dumping the output result from the Laravel controller gives:
[]
Note:
Reading a little about this issue on different posts, I changed the back-end of matplot lib to agg:
import matplotlib
matplotlib.use('agg')
print("DONE")
but nothing changed: the script works perfectly in the command line via python sample.py, the result is correctly given by executing php test.php, but in the laravel controller the result is still missing.
I am confused because it isn't a php issue due to the fact that a small php exec script will do just fine, but under laravel and apache it doesn't and it isn't an issue of file permission due to the fact that the script works if it doesn't include matplotlib.
Anyone has any ideas of what am I missing?
Are you sure there are no errors in your Python code?
Maybe the PHP is trying to run your code on a version of Python where matplotlib is not installed?

Unable to execute Python script from PHP shell_exec

I'm trying to execute a python (Python 3) script from the PHP shell_execfunction but it doesn't seem to be working, I'm trying it on a windows system but it will be in CentOS 7 in production.
In the below code snippet nothing happens when the PHP runs. But it I use the $response = shell_exec("php -v"); line it displays the PHP version ok. I've also tried running the python script directly on the command line and it runs fine with no errors.
Code
$command = "\"C:\Programs\Python\Python36-32\python.exe\" \"E:\\htdocs\\dev\\_nodes\\jobs\\jobCheck.py\" \"https:/www.google.ie\" 1";
$response = shell_exec($command);
//$response = shell_exec("php -v");
echo $response;
Command Line
"C:\Programs\Python\Python36-32\python.exe" "E:\\htdocs\\dev\\_nodes\\jobs\\jobCheck.py" "https:/www.google.ie" 1
Update #1
I've gotten the python script to run via PHP, but the python script crashes once it hits driver = webdriver.PhantomJS(), the import exists in the python script from selenium import webdriver and all this functionality works fine once called directly via the command line but doesn't seem to work once the python script is called from PHP.
Here's a sample script that prints out test 1 but not test 2 when called from the PHP script.
from selenium import webdriver
print("test 1")
driver = webdriver.PhantomJS()
print("test 2")
driver.quit()
Update #2
Looks like it was an issue with paths, there is a file created in the python script that was using a relative path, once I changed the path to be a full path the script ran ok both in the command line and when being called via the PHP script.
You need to scape the command string.
Try using escapeshellarg function.
$command = escapeshellarg('C:\Programs\Python\Python36-32\python.exe "E:\htdocs\dev\_nodes\jobs/jobCheck.py" "https:/www.google.ie" 1');
$response = shell_exec($command);
//$response = shell_exec("php -v");
echo $response;
http://php.net/manual/pt_BR/function.escapeshellarg.php

No module named lxml while requesting the url from browser/curl

I have a python code which runs in my terminal and prints the result. I wrote a php code which executes the python code using exec("python example.py argument_1"). The php code also prints the result while executing it from the terminal.
But when I try to call the php from the browser (or) through a curl request, the result of the php is not being displayed. Apache error log displays the following message.
Traceback (most recent call last):
File "./example.py", line 3, in <module>
from lxml import etree
ImportError: No module named lxml
Kindly look into this issue.
Solution :
I had conflict with the python versions
exec("/usr/local/bin/python example.py argument_1") has resolved my issue
I think you can print the sys.path(modules will be fond by python via those path ) for more details. you maybe develop your code in linux.
In linux, each user has different sys.path.
for example, I use root to run python to get sys.path in python,
'/usr/bin',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PILcompat',
'/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
'/usr/lib/python2.7/dist-packages/IPython/extensions']
use an other user to get sys.path in python
['',
'/home/mahome/anaconda2/bin',
'/home/mahome/anaconda2/lib/python27.zip',
'/home/mahome/anaconda2/lib/python2.7',
'/home/mahome/anaconda2/lib/python2.7/plat-linux2',
'/home/mahome/anaconda2/lib/python2.7/lib-tk',
'/home/mahome/anaconda2/lib/python2.7/lib-old',
'/home/mahome/anaconda2/lib/python2.7/lib-dynload',
'/home/mahome/anaconda2/lib/python2.7/site-packages',
'/home/mahome/anaconda2/lib/python2.7/site-packages/Sphinx-1.4.1-py2.7.egg',
'/home/mahome/anaconda2/lib/python2.7/site-packages/setuptools-23.0.0-py2.7.egg',
'/home/mahome/anaconda2/lib/python2.7/site-packages/IPython/extensions',
'/home/mahome/.ipython']
so, you maybe use different user to execuate your code.

"no such file or directory" in python script calling other python script in debian linux

Hi I've got the following written in a python script pythonscript1.py in linux debian in the directory /home/user/a/:
import subprocess
subprocess.call(["python" /home/user/b/phpcall.py"])
where the phpcall.py script contains:
import subprocess
subprocess.call(["php", "/home/user/b/phpscript1.php"])
individually called from console all scripts function perfectly, but when I use the first script whilst the 2nd script calls/looks for a file in directory b, rather than a, It yields the following error:
"PHP warning: include_once(something.php): failed to open stream: no such file in /home/user/b/phpschript1.php on line 25
Now it is quite clear to me the problem is that it cannot reach out of it's original directory. But I don't know what command I should add to the first script to allow the 2nd script to look in folder b.
So far google results have suggested something with "include_path='include'" but I don't know how/where to incorporate the statement succesfully.
Any suggestions on the correct syntax would be appreciated!
you can try this program:
import subprocess
import sys
proc = subprocess.Popen(
[sys.executable, '/home/user/b/phpcall.py'],stdin=subprocess.PIPE)
proc.communicate()
i think it's work. if not let know.
If the php script works only if you start it from the directory with the python script then you could use cwd parameter to change the working directory for the subprocess:
#!/usr/bin/env python
from subprocess import check_call
check_call(["php", "/home/user/b/phpscript1.php"], cwd="/home/user/b")
I've added the shebang #!/usr/bin/env python so that you could run the script directly as /path/to/phpcall.py assuming it is executable (chmod +x phpcall.py).
Note: if you want to run the python script as user user then you could specify the path using ~:
#!/usr/bin/env python
import os
from subprocess import check_call
script_dir = os.path.expanduser("~/b")
check_call(["php", os.path.join(script_dir, "phpscript1.php")], cwd=script_dir)
To avoid hardcoding the script directory, you could find it dynamically:
#!/usr/bin/env python
import os
from subprocess import check_call
script_dir = get_script_dir()
check_call(["php", os.path.join(script_dir, "phpscript1.php")], cwd=script_dir)
where get_script_dir().
For future reference the code that directly called the php script from python within was:
import os
os.chdir("/home/user/b")
os.system("php /home/user/b/phpscript1.php")
.Thanks Marc B
& I love the dynamic approach Sebastian, thank you :)

PHP exec python not working

hey yall. Im running python on a webserver from dreamhost. I am using their install of python and am using a lastfm module that can be found here: http://code.google.com/p/python-lastfm/
to get it to import properly i do this
import sys
sys.path.append("/home/myusername/build/Python-2.5/Lib/site-packages/")
import lastfm
since the lastfm module is installed there.
When I use putty to ssh into my server, i can simply run python test.py and it works perfectly. But when i run it from a php script with
exec("python test.py");
it suppossedly does not work and the script doesnt run. it runs perfectly fine when i do
import lastfm
and then have other things after,
but when i actually try to do something with the module like:
import lastfm
api=lastfm.Api(api_key)
it does not run. once again i can run the script using the same python install in a shell and it executes fine. So something must be happening that goes wrong when i run it from the php script. I figured it would be running the exact same python and everything. I checked other posts and they say it may be something with file permissions, but ive put every file to 777 and it still doesnt work. idk what the problem could be. thanks in advance everyone.
Try using the full path to the python executable. For example:
exec("/usr/bin/python test.py")
You can find the full path from the command line using the which command:
$ which python
/usr/bin/python
Whatever error python is raising would be going to the child's stderr. Try either telling php to read from stderr, or (in python) do this:
import sys
sys.stderr = sys.stdout
For Windows users:
$output = null;
exec('C:\\Python27\\python.exe C:\\sud.py', $output);
echo var_export($output, TRUE);
The code i was searching whole day ^^
That's why - hope it'll help somebody.
For Windows User -
Thanks to Karlisup my PHP file could read python.
I'm using BITNAMI WAMP in EC2 Amazon, my python file (leadatos.py) and php file are on htdocs folder.
My calling was
<?php
passthru('C:\\Python27\\python.exe leadatos.py');
?>
The last line of my Python file was print "message".
Hope it words!

Categories