在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配置。