Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Python script in PHP: capture all outputs

Tags:

python

php

I have a Python program that has multiple print statements in it. When I execute the program from PHP, the output displayed is just the value printed by the last print statement. Is there a way to capture values printed by all the print statements in the Python script?

PHP code:

<?php
ini_set('display_errors', 1);
$output = exec("python script.py");
echo $output;
?>
like image 551
raul Avatar asked May 05 '16 05:05

raul


People also ask

Can I call a Python script from PHP?

To call a Python file from within a PHP file, you need to call it using the shell_exec function.

How do I run a Python script from a PHP script?

php $command_exec = escapeshellcmd('path-to-. py-file'); $str_output = shell_exec($command_exec); echo $str_output; ?> The right privileges need to be given so that the python script is successfully executed. Note − While working on a Unix type of platform, PHP code is executed as a web user.

Can Python and PHP work together?

Yes it will work, and how risky it is depends on how good your implementation is. This is perfectly acceptable if done correctly. I have successfully integrated PHP and C, when PHP was simply too slow to do certain niche tasks in real time (IIRC, PHP is 7 times slower than its C counterpart).

Can I run PHP and Python on same server?

Absolutely possible, as a matter of fact have you heard of PiP? I have even called Python without PiP and echo out lines in an HTML table before. Works like a charm. Save this answer.


1 Answers

Try with shell_exec - Execute command via shell and return the complete output as a string

escapeshellcmd() escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands.

Name your file like- python_script.py and follow the given script-

$command = escapeshellcmd('python_script.py');
$output = shell_exec($command);
echo $output;

Ref# running-a-python-script-from-php

like image 191
Murad Hasan Avatar answered Oct 15 '22 10:10

Murad Hasan