Catch Python script output in PHP and avoid double output - php

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.

Related

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

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

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.

PHP + Python - use PHP to pass string to Python program, and parse output

I have a great Python program on my webserver, which I want to use from inside my PHP web app.
Here's an example of the python command, and output as you would see it in terminal:
>>> print MBSP.parse('I ate pizza with a fork.')
I/PRP/I-NP/O/NP-SBJ-1/O/i
ate/VBD/I-VP/O/VP-1/A1/eat
pizza/NN/I-NP/O/NP-OBJ-1/O/pizza
with/IN/I-PP/B-PNP/O/P1/with
a/DT/I-NP/I-PNP/O/P1/a
fork/NN/I-NP/I-PNP/O/P1/fork ././O/O/O/O/.
You might recognize this as a typical POS tagger.
In any case, I'm confused about how to use a PHP-based web app to send this program a string like "I ate pizza with a fork", and somehow get the response back in a way that can be further parsed in PHP.
The idea is to use PHP to pass this text to the Python program, and then grab the response to be parsed by PHP by selecting certain types of words.
It seems like in PHP the usual suspects are popen() and proc_open(), but popen() is only for sending, or receiving information - not both? Is popen() able to give me access to this output (above) that I'm getting from the Python program? Or is there a better method? What about curl?
Here are all my options in terms of functions in PHP:
http://us.php.net/manual/en/function.proc-open.php
I'm lost on this, so thanks for your wise words of wisdom!
I use exec() for this purpose.
exec($command, $output);
print_r($output);
If you want to get a little heavier / fancier... give your python script an http (or xmlrpc) front end, and call that with a GET/POST. Might not be worth all that machinery though!
You could use popen(), and pass the input to your Python script as a command line argument, then read the output from the file descriptor popen gives you, or proc_open() if you want to interact bi-directionally with the Python script.
Example 1 in the proc_open manual: http://us.php.net/manual/en/function.proc-open.php gives an example of this.
If your Python needs it as stdin, you could try popening a command line:
echo "I ate pizza!"|my_python_progam.py
and just read the output. As usual, do proper input validation before sending it to the command-line.
Something like this would work
$command = '/usr/bin/python2.7 /home/a4337/Desktop/script.py'
$pid = popen('$command',r)
........
........
.........
pclose($pid)

Categories