Python调用PHP函数实战:基于subprocess子进程的实现方案

月亮慢半拍
月亮慢半拍
发布时间:2026-10-14| 5人浏览过
原创

本文详解在Python中通过subprocess模块调用PHP文件中函数的实现方法。利用PHP命令行工具,Python开启子进程执行php命令并传递参数。文章提供了完整的PHP函数定义代码、命令行调用示例以及Python封装类代码,展示了如何处理带特殊字符的参数及多参数函数调用,适用于需要跨语言交互的开发场景。

前言

在Python中调用PHP代码的核心思路是:利用PHP命令行接口(CLI)执行PHP文件,并通过Python的subprocess模块开启子进程来运行该命令行指令。PHP函数所需的参数可以直接通过命令行参数进行传递,从而实现Python对PHP函数的调用。

测试环境

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如何调用php文件中函数的文章就介绍到这了,更多相关python调用php函数内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。