本篇文章為大家展示了利用python怎么調用php文件中的函數,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
1、操作系統:macos10.13.2
2、php版本:PHP 7.1.7(mac自帶)
3、python版本:python3.6.0
4、python庫:subprocess
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文件中的函數,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。