Skip to content
Advertisement

How to execute a Python program in PHP and use the return value inside HTML ?

How would I go about executing Python code from PHP? I belive shell_exec(Command) will run a command from the terminal. I have tried this so far:

<?php 

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

?>

In main.py it will return a value which is return randomname, I would like to put this in a <p> tag in my website.

Advertisement

Answer

Easy and quick way

To wrap your $output variable into paragraph tags you could do this.

echo "<p>$output</p>";

More modular and reusable

If you want to include this in your template, you could put your php code into a function and then call it from your template. But here, don’t echo the value, return it instead.

<?php
function getData()
{
    $command = escapeshellcmd('main.py');
    $output = shell_exec($command);
    return $output;
}
?>

And then call your function from your template.

<p><?php echo getData(); ?></p>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement