阅读量:2
在PHP中调用Python脚本有多种方法,以下是一些常见的方法:
- 使用
exec()或shell_exec()函数:
$command = "python3 /path/to/your/script.py";
exec($command, $output, $return_var);
if ($return_var === 0) {
echo "Output: " . implode("\n", $output);
} else {
echo "Error: " . $return_var;
}
?>
- 使用
system()函数:
$command = "python3 /path/to/your/script.py";
$output = system($command);
echo "Output: " . $output;
?>
- 使用
passthru()函数:
$command = "python3 /path/to/your/script.py";
passthru($command);
?>
- 使用
proc_open()函数:
$command = "python3 /path/to/your/script.py";
$process = proc_open($command, [0 => ["pipe", "r"], 1 => ["pipe", "w"], 2 => ["pipe", "w"]], $pipes);
if (is_resource($process)) {
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$error_output = stream_get_contents($pipes[2]);
fclose($pipes[2]);
proc_close($process);
if ($error_output) {
echo "Error: " . $error_output;
} else {
echo "Output: " . $output;
}
} else {
echo "Failed to start the process.";
}
?>
- 使用
popen()和pclose()函数:
$command = "python3 /path/to/your/script.py";
$process = popen($command, "r");
if ($process) {
while (!feof($process)) {
echo fread($process, 4096);
}
pclose($process);
} else {
echo "Failed to start the process.";
}
?>
请注意,这些方法可能会受到PHP配置的限制,例如safe_mode和disallow_exec()。确保在调用这些函数之前检查PHP配置。
以上就是关于“php调用python有哪些方法”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm