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.
Related
I've set up a small web app that passes user data to a python script. Python is supposed to go to work, create a file on the webserver, and allow the user to download it. However, the script execution seems to stop where the Python write() command is issued.
Python:
print("Writing to '" + filename + "'")
f = open('backups/' + filename, 'w')
f.write(self.output())
f.close()
print("Done!")
PHP:
$user = escapeshellarg($_POST['user']);
$password = escapeshellarg($_POST['password']);
$command = './backup.py '.$user.' '.$password;
print(exec($command));
Actual result:
Python does create a file in the desired directory but it remains empty. 2. Python never outputs "Done!" (Because permissions are denied)
Expected result:
Python creates a file with data
Python proceeds to print "Done!" which is output to the calling PHP script
I've done the following:
www-data has group write permissions (drwxrwsr-x) for the directory ./backup
The #!/usr/bin/env python3 shebang is present in the python file
The python file is executable
When I change to user www-data with sudo su www-data and then start the php commandline, and enter the above command invoking my Python script, the file is created correctly!
If I start a builtin php server, it also works fine, only if the php script is handled through apache, it doesn't work
I have officially wasted an entire day of my life on this.
The permissions were all right.
What was happening is that the python script failed ONLY if it was being invoked through my php script and ONLY if that was being served by Apache.
Looking through the Apache error log revealed that the python script failed because it could not write bytes to the file and ascii conversion failed because there was unicode data in the output.
So doing f = open(filename, 'wb') solved the issue.
This behaviour was not observed on my development machine or through the built-in PHP server. Still wonder why there's a difference in file handling. Would appreciate an answer if anyone has one.
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 which is needed to be run by php:
<?php
$command = escapeshellcmd('/home/Desktop/test.py');
$output = shell_exec($command);
echo $output;
?>
The out put of the python script is a binary file but I get the following error in the log:
Unable to access the X Display, is $DISPLAY set properly?
The php code works fine from the terminal but no luck when I try to run it from the browser. Any idea what is going on? Ideally, I don't want to change my program. I want to know how you can rectify the X Display error. Is there a way to check if $DISPLAY is set properly? ( I am working with Ubuntu)
I tried this : pidof X && echo "yup X server is running" on my terminal and it is saying yup x server is running!
Add the following text as the first line of your Python script:
#!/usr/bin/python
Without this, the kernel doesn't know what interpreter to run your script with, and may end up trying to launch it using /usr/bin/import (because that word probably appears on the first line of the script). The import utility requires access to the X11 display (it's a screenshot utility, basically), which is why you're getting this error.
The python file you need may need to open a window to run. You say you saw it run in terminal though? What's test.py? Is it propitiatory?
If you try using this as a command in your PHP: (not 100% that the shell escape won't strip this so may need to comment that out)
python -c \'print \"Test\"\'
and see if you get the output text back. If so it's a python issue not PHP and the test.py file may be instantiating something that needs the $DISPLAY var set. PHP doesn't set the $DISPLAY var as it is shell commands not GUI.
try popen
$command = "/usr/bin/python /home/Desktop/test.py";
$handle = popen($command, "r");
"r" for read
$read = fread($handle, 10);
10 is the size of output you want to take,
echo $read ;
hope it helps,
I am trying to run a perl script from php that requires parameters to be passed to the perl script to run correctly. The following is the correct usage of the perl script from the linux terminal:
/home/user/test.pl -a alpha -b beta
or just
/home/user/test.pl -a alpha
I have execute permissions on the script and can run it without any parameters and the correct usage from the script is displayed back to my browser.
Below is the PHP code that works by displaying the usage back to my browser:
$result = shell_exec('/home/user/test.pl');
echo $result;
And the following is the problem code which I can not for the life of me figure out:
$test = $_POST['test'];
$result = shell_exec('/home/user/test.pl -a'.' '.$test);
echo $result;
Can anyone tell me what it is that I am missing to make this work correctly?
Thank you for the help.
My issue resided within the perl script itself and a specific line that was trying to output to a log file which the apache user did not have access to. I was calling the script correctly the whole time but once I was able to get to the server side logs (granted by system admin) I saw the issue was buried within the Perl script and not in php.