前言
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
<"\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)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com
暂无“python如何调用php文件中的函数详解”评论...
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。
更新日志
2024年07月06日
2024年07月06日
- 孙露《不让我的眼泪陪我过夜》HQCDII 限量版 [WAV+CUE][517M]
- dnf巴卡尔武器怎么融合
- 魔兽世界wlk最强职业是什么 wlk最吃香最强职业推荐
- dnf巴卡尼单人和多人区别
- 群星《大热唱片DSD》APE+CUE
- 草蜢2012《软硬草蜢》3CD[WAV+CUE整轨]
- 雨林唱片发烧大碟-陈果《明知故犯HQCD》[WAV+CUE]
- 群星.2024-狐妖小红娘月红篇电视剧原声带【恒星引力】【FLAC分轨】
- 许美静.1998-好美静【上华】【WAV+CUE】
- 谭咏麟.1996-独一无二【宝丽金】【WAV+CUE】
- dnf平民怎么弄宠物
- dnf弓箭手职业
- dnf强化基础精通适合哪些职业
- V.A中国管弦乐纪念名盘《乡之音》FLAC
- [雨果]赵鹏《赵鹏·LPCD45》LPCD45[WAV+CUE]