I have made a python script for getting a directory tree. Now I am trying to call this script from php using system().
My Python Script is:
import os
from sys import argv
script, start = argv
def list_files(startpath):
directory = []
for root, dirs, files in os.walk(startpath, topdown=True):
for named in dirs:
directory.append(os.path.join(root, named))
for namef in files:
directory.append(os.path.join(root, namef))
return directory
dir = list_files(start)
My PHP command is:
$var = system('C:\\Python27\\python.exe generate -tree.py F:\\IET', $retval);
echo $var;
echo $retval;
The output that I am getting on the browser is the number '2', and when I was doing it a day before the output was coming as the number '1'.
I am new to PHP so couldn't really understand what I am doing wrong here.
Any Guidance would be appreciated!
Related
I'm trying to run a Python script from PHP using the following command:
$cmd="sudo /var/www/html/test/class.sh /tmp/tib.jpg"
exec($cmd,$output,$return)
So, i write the command into a shell script "class.sh"
cd $my_work_dir
/usr/bin/python3 -m src.inference.classify file $1
But, i can run the script in command line "php /var/www/html/test/class.sh", but that can't run in the browser with output. I use the proc_open capture the part of error:
array ( 'stdout' => '', 'stderr' => 'Traceback (most recent call last): File "/usr/lib/python3.4/runpy.py", line 170, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.4/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/bmk/1\\udce6\\udc96\\udc87\\udce6\\udca1\\udca3/0\\udce7\\udca0\\udc94\\udce5\\udc8f\\udc91/Dog/Dog-AI/dog-breeds-classification-master/src/inference/classify.py", line 7, in import tensorflow as tf File "/usr/local/lib/python3.4/dist-packages/tensorflow/__init__.py", line 24, in from tensorflow.python import * File "/usr/local/lib/python3.4/dist-
I think , because,Python can not locate my python library.
I also refered another stackoverflow Running a Python script from PHP , that is not work for me.
Can anybody help me?
try
File name should be in path of the php directory i.e where the index.php is present
$a = exec_shell("python filename.py");
Output of $a will be the output of the file.
With exec you can execute php code.
And just include your libary in the right way in the phyton file (maybe fully qualified path name)?
if you want to execute an phyton script form php:
<?php
$runcommand= escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($runcommand);
echo $output;
?>
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.
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?
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.
I am trying to activate my virtualenv using a php script or a python script but without using SSH.
This is to allow my website.com/something.py file to access certain libraries (if this can be done in another simpler way please let me know)
My PHP code is:
<?php
echo "A";
$result = exec("source ENV/bin/activate");
if ($result){
echo "Worked";
}
else{
echo "didnt work";
}
echo "B";
$result = system("python test.py");
?>
and I have test.py =
def main():
print "hello"
try:
import xlrd
except:
try:
print "xlrd didnt load"
import MySQLdb
except:
print "mdb,xlrd didnt load"
main()
The virtualenv I have setup has xlrd installed.
This is the output I get on the webpage:
Adidnt workBhello xlrd didnt load
It makes sense that xlrd didnt load but why is the source command not working? This all works in SSH
According to the docs, sourcing the activate script inside a shell just tweaks the $PATH environment variable to point to the virtualenv's bin directory. This script can't work from PHP, because an external executable can never modify the caller's environment for security reasons.
The documentation also tells you what you can do instead:
If you directly run a script or the python interpreter from the
virtualenv's bin/ directory (e.g. path/to/env/bin/pip or
/path/to/env/bin/python script.py) there's no need for activation.
So you can just specify the full path to the Python installation instead:
$result = system("ENV/bin/python test.py");