猿问

如何在 PHP 中执行 Python 程序并在 HTML <p/> 中使用返回值?

我将如何从 PHP 执行 Python 代码?我相信shell_exec(Command)将从终端运行命令。到目前为止我已经试过了:


<?php 


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

$output = shell_exec($command);

echo $output;


?>

在 main.py 中,它将返回一个值return randomname,我想将它放在<p>我网站的标签中。


明月笑刀无情
浏览 96回答 1
1回答

凤凰求蛊

简单快捷的方法要将 $output 变量包装到段落标记中,您可以这样做。echo "<p>$output</p>";更加模块化和可重用如果你想在你的模板中包含它,你可以将你的 php 代码放入一个函数中,然后从你的模板中调用它。但在这里,不要回显该值,而是返回它。<?phpfunction getData(){&nbsp; &nbsp; $command = escapeshellcmd('main.py');&nbsp; &nbsp; $output = shell_exec($command);&nbsp; &nbsp; return $output;}?>然后从您的模板中调用您的函数。<p><?php echo getData(); ?></p>
随时随地看视频慕课网APP
我要回答