I am trying to call a simple python script from a php script. The result I am getting is just a single word while my actual input is a long text/sentence. The php script should return the entire sentence; it currently outputs only "The"
Python script
import sys
print sys.argv[1]
Php script
$var1 = "The extra sleep will help your body wash out stress hormones.";
$output = exec("C:\Python27\python.exe example.py $var1");
echo $output;
Because command line parameters are space-delimited, you have to add some quotes:
$output = exec("C:\Python27\python.exe example.py \"$var1\"");
Your Python script is printing the first parameter that it receives. That first parameter is "The".
Related
I have a python srcipt, called rainbow.py. I can run it optionally with an argument. From command line
python rainbow.py, python rainbow.py 4 works well. When I call this script from php I am unable to pass the argument.
I tried:
$argument=4;
exec("python rainbow.py 4");
exec("python rainbow.py $argument");
exec("python rainboy.py .$argument");
They make the code run like there's no valid argument. (I use duration=int(sys.argv[1] in my python code, the script needs to stop after a while, and when calling from php, always the default duration is active)
I tried
$argument="4"
too, did not work.
Can you tell me what's wrong?How can I pass this argument through? I am confident with python, but a total php newbie.
part of my php code:
$argument="2";
echo "printing line <br>";
exec("python rainbow.py $argument");//duration option does not work
part of my python code:
duration=10
try:
if sys.argv[1]!=None:
print "arg found!"
duration=int(sys.argv[1])
except: pass
print "duration:",duration
I cant see the duration printing out when calling python from php, but from LEDs I can cleary see the duration is always 10 seconds
I added sudo to the python call:
exec("sudo python rainbow.py $argument")
and it works now properly. Can someone tell me why?
The python script ran without it too, but without considering the argument.
I Have been stuck for a couple of days now. I am attempting to call a simple python script from PHP. For the life of me I cannot figure out what the issue is. I have made the onoff.py script executable with chmod +x.
I can run the script just fine from the command line like this:
pi#raspberrypi:/var/www/html $ python onoff.py
LED on
LED off
My issue is when I try to call the script from PHP. I get nothing.
My Python Script:
#!/usr/bin/python
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
print "LED on"
GPIO.output(18,GPIO.HIGH)
time.sleep(1)
print "LED off"
GPIO.output(18,GPIO.LOW)
My PHP Script:
<?php
$command = escapeshellcmd('python /var/www/html/onoff.py');
$output = shell_exec($command);
echo $output;
?>
Any help is greatly appreciated!
EDIT:
if I change my onoff.py script to a simple while loop such as:
#!/usr/bin/python
x=1
while (x<10):
print x
x=x+1
the output on the browser is:
1 2 3 4 5 6 7 8 9
I just don't understand why the loop will run but I get no output with the original python code.
EDIT 2:
Ok So I taking a different approach and trying to see where the code fails. I am adding bits of code at a time. Please see the following.
#!/usr/bin/python
import random
import time
import RPi.GPIO as GPIO
randomNumber = random.randint(1, 20)
GPIO.setmode(GPIO.BCM)
#GPIO.setup(18,GPIO.OUT)
print randomNumber
Now when I run the PHP it shows a random number so I know the python script is running. When I un-comment GPIO.setup(18,GPIO.OUT) and run the php I get a blank screen. I have no idea why this would make the script fail.
shell_exec() will only return a string if $command a). Ran OK and assuming b). that it spits its response to STDOUT.
Use exec() and pass it your command, an integer $code and an empty array $response both of which are treated by PHP as arguments by reference.
Run your command thus:
$command = escapeshellcmd('/path/to/python /var/www/html/onoff.py');
$response = array();
$code = 0;
exec($command, $response, $code);
var_dump($code, $response);
die;
You should now see what is actually being given to PHP internally and why the Python script isn't working.
You need to use python before the script, i.e.:
$command = escapeshellcmd('python /var/www/html/onoff.py');
If it doesn't work, python probably ins't on the PATH of the apache user and you may need to use the full path to the python binary, use which to find the full path:
which python
//usr/bin/python
The use that value:
$command = escapeshellcmd('/usr/bin/python /var/www/html/onoff.py');
Note:
Make sure apache user has execute permissions on onoff.py
Php never get response If I use sleep for 5 minutes or more in python. Using sleep around 2 minutes , its working, I do not know what is happening, where is the problem?
Sample Code
uploadfile_database.php:
<?php
$file_id=1;
$response=exec('python /home/xyz/test.py '.$file_id);
echo $response;
?>
test.py
import os, json
import sys
sleep(300)
#sleep(420)
print "hello"
exec does not work as you're expecting. To get the output from of your python script you need to pass an output parameter to exec.
Ex.
$output = array();
$exit_code = exec('python /home/xyz/test.py '.$file_id, &$output);
You could also just use shell_exec which would work as you're expecting
I understand there are questions like mine already asked, but I can't figure this out even with the answers in those questions.
PHP:
<?php
$var1 = "hi";
$result = shell_exec('TestingStuff.py'.$var1);
?>
Python:
import sys
print(sys.argv[1])
Error received when running in Python:
IndexError: list index out of range
Both scripts are in the same folder.
Could someone please provide an answer with the code changes?
Error
If the Python script runs with no arguments at all, then that sys.argv[1] index is out of range.
Scripts
ExecPython.php
<?php
$var1 = "hi";
$result = shell_exec('TestingStuff.py ' . $var1);
echo "<pre>$result</pre>";
TestingStuff.py
import sys
if len(sys.argv) > 1:
print(sys.argv[1])
Demo
Explanation
We will start with the Python script. The goal is, that the script prints the first argument passed to it - without running into the "IndexError: list index out of range" error.
python TestingStuff.py 123 we want the output 123.
In Python the arguments passed to the script reside in sys.argv. It's a list. sys.argv[0] is always the script name itself (here TestingStuff.py). Using the example from above sys.argv[1] is now 123.
Handling the edge cases: "no argument" given.
python TestingStuff.py
This will result in an "IndexError: list index out of range" error, because you are trying to access a list element, which is not there. sys.argv[0] is the script name and sys.argv[1] is not set, but you are trying to print it and BAM goes the error. To avoid the error and only print the first argument, we need to make sure, that the list sys.argv contains more than one element (more than the script name). That's why i've added if len(sys.argv) > 1:.
That means: print the first argument only, if the list has more than 1 argument.
Now we can test the Python script standalone - with and without arguments.
And switch over to the PHP script.
The goal is to execute the Python script from PHP.
PHP provides several ways to execute a script, there are for instance exec(), passthru(), shell_exec(), system(). Here we are using shell_exec(). shell_exec() returns the output of the script or command we run with it.
In other words: if you run $result = shell_exec('php -v');, you'll get the PHP version lines in $result.
Here we are executing the Python script TestingStuff.py and add an argument, which is $var1. It's a string and added via concatenation to the string given to shell_exec(). The $result is echoed. I wrapped pre-tags around it, because i thought this is executed in the web/browser context. If you are using the scripts only on the CLI, you might drop the pre-tags.
Execution flow
the PHP script is executed
shell_exec() executes the Python script
shell_exec() returns the output of the Python script as $result
$result is printed by PHP via echo
I am executing a Python script in PHP using system(). For me to get the result of my Python script, I use print command and catch the result in PHP. Here's my code:
Python (test.py)
import sys
name = sys.argv[1]
print 'Your name is ' + name
PHP
$result = system('python test.py John');
echo $result;
/* PHP Output */
Your name is John
Your name is John
As you can see, the output is doubled. The first one was generated by the Python script itself, the second one was because of echo command. Is there a way on how to avoid this doubled output? I just wanted to catch the result and will use it somewhere on my PHP script.
**NOTE: Just wondering if there is another way on how to pass Python script output to PHP a variable. My only intention here is to put the output on a PHP variable.
You can try with exec function. It also performs a command execution but, at diference fo system, doesn't output the content to standard output. The only drawback is that the return is an array of every line in the stadard output (not a string, like system. You can also try with proc_open, that allows you redirect the output to an arbitrary pipe.