I'm trying to run a python script from PHP. The python script reads the contents from a text file and creates a PDF accordingly. When I run the Python script from terminal, it works perfectly and I get the required PDF as expected. But when I try to run the python script from PHP it gives me the following error:
Traceback (most recent call last): File "/home/amogh/server/test.py", line 3, in from fpdf import FPDF ImportError: No module named fpdf
PHP Code:
<?php
$output = shell_exec("/home/amogh/server/test.py 2>&1");
echo $output;
?>
Python code:
#! /usr/bin/python
from fpdf import FPDF
fp = open('downloads/boot.txt', 'r')
pdf = FPDF()
pdf.add_page()
pdf.set_font('Arial', '', 11)
line = fp.read()
pdf.multi_cell(200, 5, line, 0, 1)
pdf.output('test.pdf', 'F')
I've installed fpdf using this command:
pip install fpdf
I'm running my PHP files on lighttpd server. Can anyone tell me where am I going wrong?
It may be because of the different users running the script. I think that when you run it from php it is executed as user www-data
Maybe you ran pip from a virtualenv or for some other reason www-data user doesn't have access to fpdf module.
Edit:
Useful links from the comments:
How to install Python Package for global use by all users (incl. www-data)
http://nocurve.com/2018/04/23/running-python-script-from-php-as-www-data/
Related
I'm creating a web application managed with apache2, the problem I'm trying to solve is running a python script using php, I'm attaching my code:
PHP CODE:
<?php
$command = escapeshellcmd("/usr/bin/python3.6 /var/www/html/yoloface-master/showInWeb.py");
$output = shell_exec($command);
echo $output;
?>
PYTHON CODE
#!/usr/bin/python3.6
import hashlib, os, sys, cv2, PIL, subprocess, glob, numpy, django, random
from PIL import Image
import shutil
def showInWeb():
pathYolo = 'yoloface-master/'
os.chdir(pathYolo)
photo = random.choice(os.listdir("../Database/ARCHIVIOIMAGO"))
path = '../Database/ARCHIVIOIMAGO/'
print(photo)
shutil.rmtree('outputs/')
processPhoto = path + photo
command_line = ('python3.6', 'yoloface.py', '--image', processPhoto, '--output-dir', 'outputs/')
print(subprocess.run(command_line))
showInWeb();
As IDE I'm using pyCharm, and if I run the same command line in the pyCharm terminal (I'm not in a virtual environment) the program works without problems, however if I run it through the php script I get an error like "No Module Named cv2 ", this makes me guess that php is using a different version.
I read on the internet that a possible solution was to place "sudo" on the command line like:
sudo /usr/bin/python3.6 /var/www/html/yoloface-master/showInWeb.py
But I get this error:
sudo: no tty present and no askpass program specified
How can I do?
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.
Previous Research:
Running a Python script from PHP
error on using exec() to call python script
Php exec python script 'weakness'/downside
Using exec() to run python script in PHP
I am running php version 5.6.6 and python version 3.4.3 on OS X.
Basically, the problem that I am running into is that if I run a python script via command line it works find but if I run it through a PHP script (using exec()) I get this error:
AttributeError: type object 'int' has no attribute 'from_bytes'
I have created and tested a miniature isolated test case to show the problem. I have already done a chmod 777 mypy.py to make sure mypy.py is executable.
myphp.php:
<?php
exec("/usr/bin/python mypy.py 1A", $output, $return);
var_dump($output);
mypy.py:
#!/usr/bin/env python
import string
import array
import binascii
import sys
if __name__ == "__main__":
hexval = sys.argv[1]
binval = binascii.unhexlify(hexval)
binint = int.from_bytes(binval, byteorder='big', signed=False)
print("int: " + str(binint))
(I know there are better ways to accomplish what is being done in this python script, I was just making a test case that would produce the same error)
When I run python mypy.py 1F via command line, I get this printed:
int: 31
But when I run php myphp.php via command line, I get this printed:
Traceback (most recent call last):
File "mypy.py", line 11, in <module>
binint = int.from_bytes(binval, byteorder='big', signed=False)
AttributeError: type object 'int' has no attribute 'from_bytes'
array(0) {
}
(Note: I have also executed whoami from the php script just to verify that my normal user is the one running the python script)
int has no method .from_bytes in python2,/usr/bin/python uses the python 2 interpreter, you need to use /usr/bin/python3 to use your python3 interpreter.
exec("/usr/bin/python3 mypy.py 1A", $output, $return);
Making the file executable is also irrelevant as you are explicitly running it with python.
To run it as an executable and use the python3 interpreter specify the correct python version in your python shebang:
#!/usr/bin/env python3
Then:
exec("./mypy.py 1A", $output, $return);
Sorry for previous edits, I misread the question. Are you sure that python in cli and /usr/bin/python resolve to the same binary? The behavior I see tells me PHP is trying to use Python 2.x (because int object doesn't have method from_bytes).
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.
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).