本篇文章为大家展示了利用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文件中的函数,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。