欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

python如何调用php文件中的函数详解

时间:2021-10-20 08:14:06|栏目:Python代码|点击:

前言

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环境使用OpenCV检测人脸实现教程

栏    目:Python代码

下一篇:python实现KNN近邻算法

本文标题:python如何调用php文件中的函数详解

本文地址:http://www.codeinn.net/misctech/180578.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有