前言
在Python中调用PHP代码的实现逻辑是:由于PHP文件可以通过终端(Terminal)使用php命令行工具来执行,因此可以利用Python的机制启动一个子进程来运行这些命令行指令。同时,被调用的PHP函数所需要的参数,可以直接通过命令行参数的形式进行传递。
测试环境
本次测试所使用的操作系统为macOS 10.13.2。
PHP版本为系统自带的PHP 7.1.7。
Python版本为Python 3.6.0。
主要依赖的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函数的内容,欢迎搜索本站历史文章或继续阅读后续推荐内容,感谢大家的支持!