Here is what I'm trying to do:
I'm sending an Ajax request with an image as data to a php script that uploads it and execute a python script with the image name the python script loads a gender detection model and predict the gender on the person on the image.
The problem is the model doesn't load, I tried it with the php and python script in the same directory and it worked fine but I'm trying to use it in laravel so I can't do that anymore.
when I try running the python script manually like that :
python path/to/script.py
It throws this error : OpenCV(3.4.1) Error: Unspecified error (File can't be opened for reading!)
but when I do this it works:-
cd path/to/script.py ; python script.py
Here is my php:-
$file = $this->upload_Image($request->get('image'));
$path =public_path().'/app/Http/Controllers';
$command='cd '.$path.';';
$path= 'python '.$path.'/facifier.py '.storage_path('app').$file;
$command .= $path;
return exec($command);
Storage::disk('local')->delete($file);
return json_encode($orderedData);
The command ends up like this : cd absolute/path/to/script.py ; python script.py absolute/path/to/image.jpg
when I use it on a command prompt it works fine.
Here is where I get the error on my python script:-
fisher_face_gender = cv2.face.FisherFaceRecognizer_create()
fisher_face_gender.read('models/gender_classifier_model_kdef.xml')
does anyone know whats causing this, I'm on windows by the way.
thanks to bruno desthuilliers comment i got it working. The problem was in the path to model i used,its relative to the python script because i thought that the script executes on its own path not on the command promt's path .
I just changed the path to the model to the absolute path and it worked fine
Related
I'm trying to run a python script with Php but it's not running properly when I launch it with Php. This script, here "bot.py" interracts with the instagram api and writes the output as a text file in 'bot1.txt'.
Here is the Php code :
shell_exec("python automation/bot.py");
And here is the python snippet that writes in the file :
with open('../botlog/bot1.txt', 'a') as the_file:
the_file.write('Followed')
My problem is that when I launch it with Php the script runs but doesn't write in the file bot1.txt. When I run the python script with the command line everything works perfectly so I don't understand what's the deal here.
I'm working with MAMP on a local server.
Thank you !
Maybe you should specify your path to php.
$myPHPScriptPath = realpath(dirname(__FILE__));
Then specify the relative path to your python script.
Hope it helps
I am trying to run a Python script on a web server. I have been unable to run the script directly in the cgi-bin folder (kept getting 500 server errors) so I am currently attempting to call the script via a PHP script placed in the cgi-bin folder.
I am using a php script that executes a shell command on my server:
<?php
shell_exec('python /home/stevesloane8/www/cgi-bin/test.py');
?>
This method works on a few test python scripts which I have tried, but will not work on my script.
Here a portion of my script:
#!/usr/bin/python
CATEGORIES_INDEXED = ["36"]#, "6000", "6002",]
NUMBER_TO_INDEX = 25
import requests
import mysql.connector
import datetime
import time
def get_today():
today = datetime.date.today()
return today.strftime("%Y-%m-%d")
def get_start_date():
today = datetime.date.today()
start_date = today - datetime.timedelta(weeks=2)
return start_date.strftime("%Y-%m-%d")
def get_today_underscore():
today = datetime.date.today()
return today.strftime("%Y_%m_%d")
def get_token(client, secret):
payload = {"Content-Type" : "application/x-www-form-urlencoded", "client" : client, "secret" : secret}
auth = requests.post('https://integrations.apptopia.com/api/login', params=payload)
return auth.json()['token']
def get_cat_ids():
r = requests.get('https://integrations.apptopia.com/api/itunes_connect/categories', headers={"Authorization":TOKEN})
cat_dict = {}
for cat in r.json():
cat_dict[cat['id']] = cat['name'].replace(" ", "_").replace("&", "and").replace("-", "to")
return cat_dict
def pull_top_chart(cat, kind, quant):
today = time.strftime("%Y-%m-%d")
top_chart = requests.get("https://integrations.apptopia.com/api/itunes_connect/rank_lists", params={"id":cat, "date":today, "country_iso":"US", "kind":kind}, headers={"Authorization":TOKEN})
top_app_ids = top_chart.json()[0]['app_ids']
top_app_ids = top_app_ids[:quant]
rank_dict = {i:k for k, i in enumerate(top_app_ids)}
I went through it line by line and the script worked when called by the above PHP script up until I pasted in the last line:
rank_dict = {i:k for k, i in enumerate(top_app_ids)}
After I insert this line, the Python script does not run through the PHP script. It still runs when I call it from the command line.
Because this script works when I call it from the command line, is there something particular about the operation of the PHP shell_exec function that prevents this from working. Or is there some kind of permissions issue with this being run on a web server? The script permissions of both files are set to 755.
Thanks
Technically you must have certain OS privileges to Run such type of script through php.
If you good at php then
Recently I develop a script for such type of issues kindle have a look, I hope it will help
Run Complex Shell scripts through php
Happy Coding
I finally figured out what the problem was. Apache was not using my user PATH so it was calling the wrong version of Python (2.4) rather than 3.6. When I substituted the full path to the right version of Python, it worked perfectly.
running process in background on hangs PHP page
I did as explained in this above link but it did not work.
Question:
I want to send mail using Python from PHP. When I call Python, my page waits for a response from Python. I want to run Python in the background.
I also redirect Python's response to another location ex: "E:\\nil.txt", but it still waits for a response.
I am working on Windows 7. My problem is that all the answers I could find were for Linux.
My PHP code:
public static function callPython($scriptName, $data){
$path = "C:\\Users\\Aditya\\Desktop\\".$scriptName.".py";
//$data=array("to"=>$to,"name"=>$name,"headingSection"=>$headingSection,"body"=>$body,"subject"=>$subject);
$jsonArray = json_encode($data);
$jsonArray = str_replace('"', '\"', $jsonArray);
$dir= "E:\\nil.txt";
$cmd = 'python '.$path.' '.$jsonArray.' >'.$dir.' 2>&1 &';
var_dump($cmd);
shell_exec($cmd);
}
If you need my Python script, then I will post it here.
the main thing is how the python file is getting executed from the php code you have written? it is only loading the file in the $path file. and how are you getting the $data while it is not having anything as you are not storing any.
hope you get my point.
i will give you an idea.
When the php file is calling the python file. the python file should execute like we do in cmd. python some.py like this. then whatever is returned should be loaded in your php function to see it.
hope it helps
I'm converting a document file to html. I've installed LibreOffice on Linux server.
Here's the command,
$cmd = "libreoffice4.1 --headless -convert-to html /var/www/html/CV.doc -outdir /var/www/html/";
This command is working fine when I execute directly on the Linux server but when I tried to execute it via PHP it will not convert.
exec($cmd,$out,$err);
The $err is printing 127.
Kindly, let me know what I'm doing wrong here.
You say this:
This command is working fine when I execute directly on the Linux
server but when I tried to execute it via PHP it will not convert.
And your command is this:
$cmd = "libreoffice4.1 --headless -convert-to html /var/www/html/CV.doc -outdir /var/www/html/";
It could be that as a user logged into the system the path to libreoffice4.1 is part of your default user path. But when Apache (I assume) is running PHP it does not know where the libreoffice4.1 binary is.
So my solution would be to include the full path to the file in your command like this:
$cmd = "/full/path/to/this/binary/libreoffice4.1 --headless -convert-to html /var/www/html/CV.doc -outdir /var/www/html/";
Of course replacing /full/path/to/this/binary/ with the actual path to the file.
You can easily determine the full path to the binary by logging into your sever & typing in the following command:
which libreoffice4.1
The returned output should be the full path your libreoffice4.1 binary file. The path should be something like this:
/usr/bin/libreoffice4.1
Or this:
/usr/local/bin/libreoffice4.1
But the which command on your system will return the full path to the file, so use that output as your guide.
The most common reason for this is that the $PATH environment variable hasn't been populated to your PHP application. In this case use the full path to libreoffice:
$cmd = "/usr/bin/libreoffice4.1 --headless ... ";
The path /usr/bin may differ on your system. Type which libreoffice4.1 in terminal to find it out.
Another reason for the problem might be insufficient permissions to write files into the target directory or read the original documents. In this case make sure that the php application has proper permissions to do so. !root permissions must not being required for that! This would be a security flaw in your application.
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!