Unable to call a python script through PHP - php

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

Related

Passing argument from PHP to Python not working

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.

Passing PHP variable into a Python script not working

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".

How to get response from python to php?

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

PHP variable into Python

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

Executing python commands from php script

I have installed SymPi in the server and from the command line, I am able to execute the following.
python ./sympy-0.7.5/bin/isympy
(this will open a console where I can type mathematical expressions. then the following expression)
1 + 2
(will give 3 as output)
My aim is to do the same from php using shell_exec. I have written a php file as given below, but is not working.
$command = escapeshellcmd('python ./sympy-0.7.5/bin/isympy');
shell_exec($command);
$output = shell_exec('1 + 2');
Can anybody help me to figure out why this is not working?
Please note that the following script works fine which just execute a python script and retrieve the output.
$command = escapeshellcmd('python C:\PythonPrograms\test3.py');
$output = shell_exec($command);
echo $output;
My guess is that the working directory (cwd) of shell_exec is different from the one you're in when you execute it manually.
Your working example specifies a hard path that will work from anywhere. Whereas your not-working example specifies a relative path (./ is the cwd).
Convert your call to isympy to give its full path on disk. Or figure out how to set the cwd of shell_exec.
(If this doesn't solve it, say more than "is not working." What happens? An error? What is the full text of the error?)
Each time you run shell_exec, it opens a completely new instance of the shell.
Edit:
You can pass a command for python to execute like this:
$expression = '1 + 2';
$cmd = 'python -c \'print "%f" % (' . $expression . ')\'';
$output = shell_exec($cmd);
This, admittedly is not using sympy, but for simple mathmatical expressions you may not need to. If you do, you would just need to import the library in the same command, like this: python -c 'import sympy; print "%f" % sympy.sqrt(3)'
I could manage the desired result in a different way.
Created a python script which accepts the expression as the command line argument , execute and display the output.
Call this script from php by passing the expression as the command line argument.

Categories