从PHP运行Python程序


在PHP中,可以使用`exec()``shell_exec`函数。它可以通过shell执行,结果可以作为字符串返回。如果从命令行传递NULL或根本没有输出,则返回错误。

`exec()` 函数

exec函数用于在shell和外部程序的命令行中执行命令,并可以选择捕获输出的最后一行。

语法

exec(string $command, array &$output = null, int &$return_var = null);

`shell_exec()` 函数

shell_execexec类似,但它捕获并返回命令的整个输出作为字符串,而不是仅返回最后一行。

语法

shell_exec(string $command);

从PHP运行Python程序

这个过程包括以下几个步骤。

  • 准备Python脚本

  • 准备PHP脚本

  • 设置权限

  • 运行PHP脚本(从命令行或Web服务器)

准备Python脚本

以下代码行指的是Python脚本

# test.py
print("Hello from Python!")

准备PHP脚本

下一步是创建一个PHP脚本,使用`exec``shell_exec`函数执行Python程序。

< ?php
// To Run the Python program 
$command = escapeshellcmd('python3 /path/to/test.py');

// Use shell_exec to execute the command and capture the output
$output = shell_exec($command);

// Display the output
echo $output;
? >

设置权限

确保PHP有权限执行Python程序并访问任何必需的文件或目录。

chmod +x /path/to/test.py

从Web服务器运行PHP

将PHP脚本放置到Web服务器的文档根目录中。现在可以通过Web浏览器访问PHP脚本。

https:///test.php

从命令行运行

我们可以从Web服务器或命令行运行PHP脚本。

php /path/to/test.php

输出

Hello from Python!

更新于:2024年9月10日

5K+ 浏览量

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.