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;
?>
To call a Python file from within a PHP file, you need to call it using the shell_exec function.
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.
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With