我尝试在php脚本中运行python脚本,我的python文件创建了一个绘图,我希望该绘图显示在php页面中。但是当我运行代码时,它没有显示任何内容。有人知道为什么吗?请告诉我怎么解决这个问题?Python代码:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')Php脚本
<?php
$command = escapeshellcmd('python test.py');
$output = shell_exec($command);
echo $output;
?>发布于 2021-02-02 20:20:07
更新答案:
我已经复制了您的问题,并通过对PHP和Python文件进行了一些更改来解决。
尝试这些修改:
test.py:
#!/usr/bin/python -u
import matplotlib.pyplot as plt
import sys
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.savefig(sys.stdout)在顶部添加环境注释可以确保python在从PHP调用时在正确的环境中运行。
最后一行确保python将生成的图像输出到stdout,以便PHP可以接收它。
PHP文件:
<?php
// use output buffering to prevent passthru outputting the returned image code immediately.
ob_start();
passthru('python test.py');
// Store the binary image data (png format) to $raw variable
$raw = ob_get_contents();
ob_end_clean();
?>
<!-- output the image by base64_encoding it -->
<!-- could also look at using GD to store the image to a file on the webserver for direct access in HTML -->
<img src="data:image/png;base64, <?=base64_encode($raw)?>" alt="image" />这两个文件应该导致PHP运行python命令,将返回的二进制图像存储到$raw变量,并使用输出缓冲来防止passthru自动将输出转储到浏览器。这里优先使用Passthru,而不是exec或shell_exec,因为它处理正确运行的命令的二进制输出(exec将返回的图像二进制拆分成各种不同的数组元素,这些元素并不总是很容易重组。
关于评论的解释,原文如下。
在使用shell_exec时,您必须使用echo语句将命令链接起来才能获得结果。例如,像这样:
shell_exec("python test.py 2>&1; echo $?");考虑使用exec($command, $output) -注意exec的参数,以确保返回输出值。还有一个可选的第三个参数,它可以让你检查任何结果代码。(手册请参阅:https://www.php.net/manual/en/function.exec.php )
像往常一样,运行像这样的相对较高级别的命令-要非常小心。
https://stackoverflow.com/questions/66009499
复制相似问题