python如何呼叫php檔案中的函式詳解
阿新 • • 發佈:2020-12-31
前言
python呼叫php程式碼實現思路:php檔案可通過在terminal中使用php命令列進行呼叫,因此可使用python開啟子程序執行命令列程式碼。函式所需的引數可通過命令列傳遞。
測試環境
1、作業系統:macos10.13.2
2、php版本:PHP 7.1.7(mac自帶)
3、python版本:python3.6.0
4、python庫:subprocess
呼叫php函式
php命令列呼叫php檔案中的函式
php檔案:test_hello.php
<?php function hello_world($s1) { $str1 = $s1; echo $str1; echo "\n"; } function hello_world2($s1,$s2) { $str1 = $s1; $str2 = $s2; echo $s1; echo "**********"; echo $s2; echo "\n"; } // 獲取引數,索引為0為呼叫的檔案路徑,索引為1為呼叫的函式,索引為2為函式傳入引數$s1,索引為3為函式引數$s2 var_dump($argv); // exit; // 呼叫函式 $func_name = $argv[1]; if ($func_name == "hello_world") { // 引數1 $param1 = $argv[2]; hello_world($param1); } elseif ($func_name == "hello_world2") { // 引數1 $param1 = $argv[2]; // 引數2 $param2 = $argv[3]; hello_world2($param1,$param2); } else { echo "the function $func_name is not exist !"; } ?>
terminal執行php命令
# 字串中包含空格、逗號、反斜槓,需要使用""來確定為1個引數 php -f test_hello.php hello_world "My name is John\\,age is 20." php -f test_hello.php hello_world2 "My name is John\\,age is 20." "My hometown is BaoDing." php -f test_hello.php hello_world3 "My name is John\\,age is 20."
執行結果
python子程序執行php命令列
python檔案:test.py,將test_hello.php與test.py放在同目錄下執行
import subprocess class Test(object): def run(self,cmd): proc = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE) # 開啟子程序 res = proc.stdout.read() if res: res = res.decode() return res cmd1 = 'php -f test_hello.php hello_world "My name is John\\,age is 20."' cmd2 = 'php -f test_hello.php hello_world2 "My name is John\\,age is 20." "My hometown is BaoDing."' cmd3 = 'php -f test_hello.php hello_world3 "My name is John\\,age is 20."' obj = Test() for i in [cmd1,cmd2,cmd3]: res = obj.run(cmd1) print(res) print("*" * 10)
到此這篇關於python如何呼叫php檔案中函式的文章就介紹到這了,更多相關python呼叫php函式內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!