在PHP中调用Python脚本有多种方法,以下是一些常见的方法:
exec()
或 shell_exec()
函数:<?php
$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()
函数:<?php
$command = "python3 /path/to/your/script.py";
$output = system($command);
echo "Output: " . $output;
?>
passthru()
函数:<?php
$command = "python3 /path/to/your/script.py";
passthru($command);
?>
proc_open()
函数:<?php
$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()
函数:<?php
$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配置。