Python script won't exec from php when specific library is used - php

Im trying to execute a Python script to get and set the parameter server in ROS. When I run any other simple python script that for example prints "Hello", I get back the value in PHP. But when I run this code:
#!/usr/bin/env python
import roslib
import rospy
import sys
import re
import string
get = rospy.get_param("param")
print get
I get an empty echo. However this code works fine in the terminal!
All I'm doing in PHP is:
$output = exec("python path/script.py")
echo $output;
I tried shell_exec, I tried with python in the command, and without. I also tried /usr/bin/python still it won't work for this specific code, but everything works for a simple print!

It turns out that Apache's user doesnt have the required environment variables. So you have to add the environment variables paths you need in Apache's.. You can set them out here

Related

Python package not imported when executed through 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');

How to fix no output with python linked to php?

I have a python script which takes data from a csv file via pandas. When I run this solely this works fine. But when I run it within php it does not work. I want it to work like that so I can output the python output onto the website.
Python code:
#!/usr/bin/env python
import pandas as pd
teams = pd.read_csv("/var/www/html/teams.csv")
print(str(teams['punt'][0]))
PHP code:
<?php
$command = escapeshellcmd('python3 /var/www/html/python.py');
$output = shell_exec($command);
echo $output;
?>
Under the PHP is some irrelevant html code. It would be very helpful if someone could help me!
EDIT:
When I run the php in terminal it does not give any errors and it gives the result perfectly. But when I run localhost it does not work but I cannot seem to find any errors. I also tried running a different python script which only prints "hello" and when I try that the code does work and the text shows up in the browser.

Apache doesn't let PIL work

I wrote "Apache doesn't let PIL work" as title but I'm not sure about if this is the case or not.
I have a php script that sends json data to a py file that will process an image according to this json data. The communication between languages works. But when I add the line for importing PIL to py file, php returns NULL on browser. It's also working when I run the php script with command line but I have to run it on web browser.
This is the php script:
<?php
$result = exec('python somecode.py ' . escapeshellarg(json_encode('897')));
$resultData = json_decode($result, true);
var_dump($resultData);
?>
this is the py file:
import sys, json
data = json.loads(sys.argv[1])
print data
this works just fine and gives me the output of int(897) which is expected. When I add the line of from PIL import Image, it gives NULL on browser but it still can being ran on command line without any problem. I didn't even add the code for processing image, just trying to import PIL.
EDIT: I tried to import numpy, it didn't prevent the code from running. It runs on browser even I import numpy. So, probably problem is related with PIL.
It was about the image's path. I changed it to a proper one, and the problem is fixed.

Strange issue running Python script in php in browser

I am using python's nltk to do some interesting things to input strings from php, but I'm experiencing some difficulties in getting it to output to the browser. My code looks like this:
system("python test.py command line arguments");
which outputs correctly in the command line no matter what is in my test.py file. However, in the browser it will work unless specific code is present.
inside test.py:
import string
import sys
from nltk import word_tokenize as wt
from nltk.corpus import wordnet as wn
x = ""
for item in sys.argv: x += item+" "
i = wt(x)
result = ""
wn.morphy(i[0])
print "hello world"
This will not print "hello world" in the browser, but only if the preceding line of code is present. without
wn.morphy
it will run. Unfortunately I need to use wn.morphy. Why would this not work in the browser with that specific line of code in my test.py file? I have already turned off safe mode, which is what allows me to output to the browser with python at all
Actually, this code works for me on the PHP CLI, whether or not I include the wn.morphy line, so I think your problem is elsewhere, or version-related.
Did you remember to download the 'wordnet' corpus? If not, run
>>> import nltk
>>> nltk.download('wordnet')
in Python, and then try again. I could see the script erroring out because it can't get to the corpus.
What is the error? Could it be due to the size of WordNet (which is pretty big) or the time it takes Python/NLTK takes to load it? A live web server is probably going to have tighter quotas than an interactive console session.

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