從PHP執行Python程式
在PHP中,可以使用`exec()`或`shell_exec`函式。它可以透過shell執行,結果可以作為字串返回。如果從命令列傳遞NULL或根本沒有輸出,則返回錯誤。
`exec()` 函式
exec函式用於在shell和外部程式的命令列中執行命令,並可以選擇捕獲輸出的最後一行。
語法
exec(string $command, array &$output = null, int &$return_var = null);
`shell_exec()` 函式
shell_exec與exec類似,但它捕獲並返回命令的整個輸出作為字串,而不是僅返回最後一行。
語法
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!
廣告