PHP variable into Python - php

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

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.

How to execute C code through PHP by prompting terminal

I have a C code that I have to execute through PHP,
I have used exec('./sys'), sys is my executable file.
I have also tried system(), passthrough(), shell_exec() and they are not giving output.
When I executed exec('who'); it gives the output.
What can I do to execute sys?
Each of those methods you reference will execute your sys file, but you need to make sure you are executing the correct path. Your working path is determined by what script is actually executing PHP. For example, if you're executing your code through apache or the command line your working directory may be different. Lets assume this file structure:
+ src/
| + script.php
| + sys
I would recommend using PHP's __DIR__ magic variable in your script.php to always reference the current file's directory, and then work from there:
// script.php
exec(__DIR__ . "/sys");
Retrieving output can be done a couple different ways. If you want to store the output of the script in a variable, I would recommend using exec according the the manual:
Parameters ΒΆ
command
The command that will be executed.
output
If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n, is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().
return_var
If the return_var argument is present along with the output argument, then the return status of the executed command will be written to this variable.
exec will return the first line of output, but if you want more than that you need to pass a variable by reference:
// script.php
$output = array();
exec(__DIR__ . "/sys", $output);
$output will then contain an array of each line of output from the command. However if you want to run your sys script and directly pass through the output then use passthru(__DIR__ . "/sys"); For example, if you wanted to execute a command that required input on the command line, passthru would be the best option.

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

Catch Python script output in PHP and avoid double output

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.

php exec() and shell_exec()

I currently have a php page that my webserver serves. In order to display all the information I need to display on the page I need output from an external python script. So I have been using the exec() command of php to execute the python script and capture the output in an array of strings as follows:
$somequery = $_GET['query'];
$result = exec("python /var/www/html/query/myscript.py ".somequery."");
//some for loop to loop through entries in result and echo them.
However there are never any entries to be printed, yet when I run the command directly on the console of the server it will output correctly. I've tried echoing out the command on the webpage that I am executing and it's the correct command. The only thing I think it can be is that exec() doesn't stop the rest of the php program from executing before it finishes, leading to the loop i have printing out entries finding that $result is empty.
How can I ensure that exec() finishes executing before the rest of my php script? Are there maybe settings in php.ini that I would need to change? I'm not entirely sure.
EDIT: I've tried running and storing the output of shell_exec("echo hello"); and printing that output, it now prints. However, when running my command that takes a few seconds longer, the program never finishes executing it before going to the next line.
EDIT 2: I found my solution in the following post https://stackoverflow.com/a/6769624 My issue was with with the numpy python package I was using and I simply needed to comment out the line in /usr/lib64/python2.7/ctypes/init.py like the poster did and my script output correctly.
The correct way to get your shell output is like this:
exec("python /var/www/html/query/myscript.py ".somequery."", $result);
var_dump($result); //output should be in here
Give it a try.

Categories