如何从Python脚本向PHP函数传参并获取返回结果?
解决Python调用PHP带参函数的问题
有几种可行的方法实现Python动态调用PHP的start()函数并传入参数,下面是最常用的两种方案:
方法1:让PHP脚本接收命令行参数
这是最直接的方式,修改PHP脚本使其读取命令行传入的参数,再调用目标函数:
<?php function start($height, $width) { return $height * $width; } // 读取命令行参数,argv[0]是脚本文件名,argv[1]、argv[2]为传入的参数 if (isset($argv[1]) && isset($argv[2]) && is_numeric($argv[1]) && is_numeric($argv[2])) { $height = (int)$argv[1]; $width = (int)$argv[2]; echo start($height, $width); } else { // 参数不合法时输出提示 echo "Invalid parameters"; } ?>
对应的Python脚本调用时,直接将参数作为命令行参数传入:
import subprocess # 定义要传入的动态参数 height = 10 width = 15 result = subprocess.run( ['php', './check1.php', str(height), str(width)], stdout=subprocess.PIPE, check=True, text=True # 直接获取字符串结果,无需手动解码字节串 ) print(result.stdout) # 输出结果:150
方法2:通过标准输入传递参数(适合复杂参数场景)
如果需要传递复杂结构的参数(比如JSON、数组),可以用标准输入的方式传递:
修改PHP脚本读取标准输入内容:
<?php function start($height, $width) { return $height * $width; } // 读取标准输入的内容 $input = file_get_contents('php://stdin'); $params = json_decode($input, true); if (isset($params['height']) && isset($params['width']) && is_numeric($params['height']) && is_numeric($params['width'])) { echo start($params['height'], $params['width']); } else { echo "Invalid parameters"; } ?>
Python脚本通过标准输入传递JSON格式的参数:
import subprocess import json # 构造复杂参数结构 params = { 'height': 10, 'width': 15 } result = subprocess.run( ['php', './check1.php'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, check=True, text=True, input=json.dumps(params) # 将参数转为JSON字符串传入标准输入 ) print(result.stdout) # 输出结果:150
内容的提问来源于stack exchange,提问作者user20907770
相关产品推荐
相关产品推荐

