Laravel + Apache executing Python script with matplotlib - php

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?

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');

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

Import caffe in python in php code

I have a test.php code
$b = system("python test.py", $a);
echo $a;
and the python test.py code
import caffe
print('!')
when I use php test.php in server by console, it is ok and print !0. But when I view the test.php in brower, it will has some errors and print 1. But I don't know what's wrong because the python run via system function.
I think your problem is based in permission: when you run test.php in console, this script is executed with your user, but when run test.php in web browser, this script is executed with webserver user (www-data probably).
I suggest to use a more simple py script:
print('!')
in order to check that the problem is due to permission and nothing else.
What operating system are you using?

Not getting output from python script when run through PHP

I have a python script that prints out the program names that are currently in the volume mixer in Windows 10.
This works fine when I run it in the cmd.
C:\wamp\www\Volume>py test.py
firefox.exe,Spotify.exe,Microsoft.Photos.exe,Steam.exe,
and here is my python script.
import sys
from pycaw.pycaw import AudioUtilities
def main():
list = ''
sessions = AudioUtilities.GetAllSessions()
for session in sessions:
volume = session.SimpleAudioVolume
if session.Process and session.Process.name():
list += session.Process.name() + ','
sys.stdout.write(list)
if __name__ == "__main__":
main()
And my PHP:
$python = "py";
$script = "test.py";
exec("$python $script 2>&1", $output);
print_r($output);
But when I run it in PHP using WAMP, I don't get any output from that script, nothing is outputted.
If I change my python script to only contain "print("TESTING")" then I can read that output fine in PHP which makes me think that my python code is failing perhaps due to permissions. So I changed the user from SYSTEM to my own user so when I use:
echo exec("whoami") // Outputs my user account name
I thought maybe my PHP script was off, so I tried running it though the command line, but the results are what I want:
C:\wamp\www\Volume>php index.php
Array
(
[0] => firefox.exe,Spotify.exe,Microsoft.Photos.exe,Steam.exe,
)
So I'm at a loss as to why when I execute my PHP code through my browser, I am not getting any output unless my python script only contains :
print("TESTING")
What could possibly be going wrong?
EDIT
So I decided to debug this further by altering my python script to create a .txt file on my desktop, this works fine when running it through the command line. But again, when I run it through my browser/PHP, that file isn't created. So maybe I need to grant special permissions to my python script? I'm not sure why I need to do that though as I have given PHP my user account
So I think I found out why I'm not getting any output from my python script, thanks to #Torxed.
It seems like when I run the Python script through WAMP/PHP it must run as a different user/environment which doesn't have any Audio.
This is odd however as I've set 'wampapache64' to run as my user account, even after a restart I'm still getting the same results.
I've even tried
runas /savecred /noprofile /user:<USER>
But that just returns the password prompt which I won't be able to fill out in PHP.
This project looks like a dead end for now.

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