Image Processing (OpenCV with PHP) - Issue with the exec command - php

I have setup OpenCV 3.0 with python3.4 binding on ubuntu 14.04. I run OpenCV using virtualenv. So, everytime I have to run the workon cv command.
Now I want to run a python script that uses OpenCV library from PHP using the exec command.
exec("workon cv");
exec("python3 hough_circles.py")
This is the error :
sh: 1: workon: not found
Traceback (most recent call last):
File "hough_circles.py", line 1, in <module>
import cv2
ImportError: No module named 'cv2'

Two issues...
1. PATH to workon
The error message is telling you it doesn't know where workon is, so you better tell it the full path to where it is so exec() can find it, e.g.:
exec("/usr/local/bin/workon cv");
The /usr/local/bin above is just an example, if you want to know where it is on your system, run:
which workon
and use the output.
2. Subprocesses are independent
Even when you have got that set correctly, the process that executes workon then exits and you start a fresh, shiny new one - in which you have not run workon. So, you better do both things in the same process like this:
exec("/usr/local/bin/workon cv && /path/to/python3 hough_circles.py");

Related

Having trouble executing Python script from PHP because of an ImportError

I'm trying to execute a Python script from PHP using exec() like this:
echo exec("/usr/bin/python3 timedttp.py 2>&1");
I get ImportError: No module named 'mpld3'. I'm running this with Apache on a Raspberry Pi. The Python program is located in the same directory as my php file, and whenever I run the script in the terminal there are no problems at all. Also tried using shell_exec() and the error I get is the following one:
Traceback (most recent call last): File "timedttp.py", line 6, in import matplotlib.pyplot as plt, mpld3 ImportError: No module named 'mpld3'
I'm calling the module like this inside my Python script:
import matplotlib.pyplot as plt, mpld3
I can run this program wihtout any issues from the terminal, so I think this is Apache or PHP related.
I'd really appreciate any help I can get with this.

Python modules are not imported when running python script from PHP

I have a Python script, which works fine when I run it in Terminal. Here it is:
import bs4, requests, json, sys
from sys import argv
def getFsmonData(link):
res = requests.get(link)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text)
# Get table data
tds = soup.select('td')
new_td_list = []
for i in range(len(tds)):
inner_td_list = []
for y in range(len(tds)):
inner_td_list.append(tds[y].getText())
new_td_list.append(inner_td_list)
print(inner_td_list)
td_list_json = json.dumps(inner_td_list)
tdf = open("/path/to/file/data/td_data.txt", "w")
tdf.write(td_list_json)
tdf.close()
getFsmonData(sys.argv[1])
But now I am trying to run it from PHP and I get the following error:
Traceback (most recent call last): File
"/path/to/file/example.py", line 1, in import bs4, requests,
json, sys ModuleNotFoundError: No module named 'bs4'
I guess PHP thinks I do not have this module installed, but I am not sure of course. Here is my PHP code:
<?php
$link = $_POST['dn-link'];
if (isset($_POST['submit'])) {
system('/usr/bin/python3 /path/to/file/example.py ' . escapeshellarg($link) . ' 2>&1', $retval);
}
?>
Who can help solving this issue?
Most likely, when your PHP script executes your Python script, its executing it as a different user (possibly super user). What you can do is check if the packages are installed under the super user by doing
sudo pip list
or if you're using python3
sudo pip3 list
see if the packages you we're wanting to use are listed from this command.
If they aren't listed, you can easily install them via the command:
sudo pip install <pkg name>
or
sudo pip3 install <pkg name>
What you're doing here is installing the packages under the super user rather than you the local user.
I think your misunderstanding the permission issue. It's not that you need to add it PHP. It's that your OS keeps track of permissions, and the permission you have assigned to your PHP interpreter and your Python interpreter are misaligned. There are two permissions that usually people mix up here - USER which is login level access and SYSTEM which is system wide access. If your on your own dev machine then add both to SYSTEM.
We need to know your OS to be able to fully answer, i'm going to guess Mac OS in which case would be this (I think, can't test it right now).
sudo nano "pathOfYourInterpreter"
The other thing could be happening is that the libraries you're tryng to import are somewhere where the current sys path you have setup can't reach them. For example if you have your sys variable for Python set to the directory where the interpretor is but the scripts you're importing are in a different folder. In that case you have several options for accessing those scripts.
Set the current working directory to the folder where they're located before importing with:
os.chdir("locationOfScript/")
import script.py
Add a sys Path at runtime:
sys.path.append("locationOfScript/)
There are more methods of attack, but I think this should get you started.

Php (Synology) - From apache and command line, it get different result when executing external program

I use exec() / shell_exec() / system() to execute synology downloadstation cli program like below:
system("downloadstation 2>&1");
I use ssh to test php and it will return the correct result
$ php testworld.php
However I use website to test the result.
It will display
Traceback (most recent call last): File "/usr/bin/downloadstation",
line 16, in import optparse, sys, os, datetime, time, re, pyPgSQL
ImportError: No module named pyPgSQL
Nas system have python2.4 and python2.7. And only python2.4 have PyPgSQL.
My system information is like below:
System default "python" is python2.4.
/usr/lib/ only have python2.7 folder
Python2.4 path : /volume1/#optware/lib/python2.4/
PyPgSQL path : /volume1/#optware/lib/python2.4/site-packages/pyPgSQL
And I already test the normal program and it will return the same result:
system("ls");
How to fix this issue ?

PHP shell_exec() in ubuntu

I am using ubuntu with libreOffice. I have installed unoconv for convert a *.odp file to *.pdf. When i run the command unoconv -f pdf myfile.odp from terminal then it works very fine. I want to do the same thing with using PHP shell_exec() method. So, I wrote the following code:
$output = shell_exec('unoconv -f pdf test.odp 2>&1');
echo $output;
But it shows the following error:
/usr/bin/python: /opt/lampp/lib/libz.so.1: no version information available (required by /usr/bin/python)
Traceback (most recent call last): File "/usr/bin/unoconv", line 24, in import uno,
unohelper File "/usr/lib/python2.7/dist-packages/uno.py", line 34, in import pyuno SystemError: dynamic module not initialized properly
How can I solve this problem?
Thanks in advance.
its the same error for me as well.. but if we run it with exec() it shows some different error.
Moreover the HTTPD of apache runs as user nobody that is the main issue behind it. if it can run by root user then problem will be solved.

What is the difference between running a script from the command line and from exec() with PHP?

I'm trying to run a Python script using exec() from within PHP. My command works fine when I run it directly using a cmd window, but it produces an error when I run it from exec() in PHP.
My Python script uses NTLK to find proper nouns. Example command:
"C:\Python25\python.exe" "C:\wamp\projects\python\trunk\tests\find_proper_nouns.py" "I went to London this morning"
returns [London] when I run it from cmd, but throws an error in the Apache log when I run the same command from exec().The script is defintely getting run OK - if I change the python script to be print "Hello World" that is returned fine.
I know it's a big ask for anyone to know how to fix this NLTK error, but I could really do with any pointers as to why running it from exec is different to cmd. (The command is identical).
I'm running WAMP on Windows 7 with Apache 2.2.11.
Here's the error in the Apache log:
Traceback (most recent call last):
File "C:\wamp\projects\python\trunk\tests\find_proper_nouns_command_line.py", line 6, in <module>
parts = nltk.pos_tag(text)
File "C:\Python25\lib\site-packages\nltk\tag\__init__.py", line 62, in pos_tag
tagger = nltk.data.load(_POS_TAGGER)
File "C:\Python25\lib\site-packages\nltk\data.py", line 590, in load
resource_val = pickle.load(_open(resource_url))
File "C:\Python25\lib\site-packages\nltk\data.py", line 669, in _open
return find(path).open()
File "C:\Python25\lib\site-packages\nltk\data.py", line 451, in find
raise LookupError(resource_not_found)
LookupError:
**********************************************************************
Resource 'taggers/maxent_treebank_pos_tagger/english.pickle' not
found. Please use the NLTK Downloader to obtain the resource:
>>> nltk.download().
Searched in:
- 'C:\\nltk_data'
- 'D:\\nltk_data'
- 'E:\\nltk_data'
- 'C:\\Python25\\nltk_data'
- 'C:\\Python25\\lib\\nltk_data'
- 'C:\\Windows\\system32\\config\\systemprofile\\AppData\\Roaming\\nltk_data'
**********************************************************************
You have to run nltk.download() and choose 'maxent_treebank_pos_tagger'. You must make a python script and in it put:
#!/usr/bin/python
import nltk
nltk.download('maxent_treebank_pos_tagger');
then run it from command line. It will install the data files for the POS tagges, which you don't have installed yet.
After you do this it should work.
Your web server likely runs with other privileges than yourself. Possible problems include:
Path/file permission: can the web server user access the files it needs?
Different environment: are all necessary environment variables (PATH, Python-specific stuff, …) set?
Configuration: are there per-user configurations for Python or the module?
Tip: execute set in both the command prompt and from the PHP process and check the differences.
From the shell/terminal, you can use:
sudo python -m nltk.downloader maxent_treebank_pos_tagger
It will install maxent_treebank_pos_tagger (i.e. the standard treebank POS tagger in NLTK).

Categories