Fullstar

Archives

  • December 2025
  • August 2024
  • July 2024
  • February 2024
  • November 2023
  • August 2023
  • July 2023
  • January 2023
  • November 2022
  • October 2022
  • September 2022
  • February 2022
  • January 2022
  • September 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020

Categories

  • Code
  • Lens
  • Life
0
Fullstar
  • Code

php调用python脚本

  • July 5, 2020
  • Brandon
Total
0
Shares
0
0
0

1.php使用exec函数,函数原型:

string exec(string $command [, array &$output [, int &$return_var]])

2.php使用system函数,函数原型:

string system(string command [, int $return_var])

实例:

<?php
    exec("python test.py 100",$date,$ret);
    echo($date[0]);
    //上述代码表示使用python解释器调用test.py,并传入100作为参数,$date为.py文件的输出值,且输出形式为print(),而不是return,$ret判断是否调用成功,成功为0,否则为非0值
?>
import sys
list = sys.argv
print(list[1])
#sys.argv是一个参数列表,这个列表存放着从外界获取到的参数(可能有多个),list[0]默认代表执行的py文件相对于当前工作目录的路径,因此从外界得到的值由[1]开始

注意:在调用过程中可能有各种错误的发生,可使用如下指令进行替换以观察错误原因:

exec("python test.py 2>&1",$ret);
print_r($ret);
#替换为上述指令后在浏览器中执行时将会直接输出错误原因

坑点:

1.若php在命令行模式下正常运行而在浏览器中无法运行则很可能为权限问题,将代码所在文件权限设置为apache即可:

chown -R apache:apache /var/www/html/wordpress/forTest

2.当php使用exec/system向python传递参数时,由于参数以空格划分,因此若所传递的参数为字符串且字符串带有空格,则应在传递此参数前为其加上双引号,则传递至python时才能将其视为一个字符串整体

3.当 php使用exec/system向python传递中文参数时,会报错utf8无法解码等错误,目前的解决方案为使用mysql数据库中转,暂未找到其他解决方案。。。 (PS: 可尝试此方法: PHP接收Python的传值 【php向python传值】)

参考链接:

  • sys.argv的意义及用法
  • PHP exec函数调用执行 Linux Shell命令及错误码解析
  • php连接mysql数据库
  • Python连接MySQL数据库【注:由于python3取消了MySQLdb,因此需先引入代码:[import pymysql pymysql.install_as_MySQLdb()]再引入 MySQLdb 才能正常使用】
Total
0
Shares
Share 0
Tweet 0
Pin it 0
Brandon

Previous Article
  • Code

华为云鲲鹏服务器安装wordpress

  • July 5, 2020
  • Brandon
View Post
Next Article
  • Code

将python脚本挂至服务器后台自动运行

  • July 5, 2020
  • Brandon
View Post
You May Also Like
View Post
  • Code

WordPress 后台任务利器:使用 BGRunner 构建可靠的异步处理

  • Brandon
  • December 14, 2025
View Post
  • Code

WordPress image offload

  • Brandon
  • December 14, 2025
View Post
  • Code

ComfyUI应用手册

  • Brandon
  • December 6, 2025
View Post
  • Code

Leetcode Java常用代码

  • Brandon
  • February 17, 2024
View Post
  • Code

Golang入门

  • Brandon
  • February 4, 2024
View Post
  • Code

Setting Up and Maintaining a Ubuntu Environment for My Home Server

  • Brandon
  • November 24, 2023
View Post
  • Code

Swift Learning Log

  • Brandon
  • August 31, 2023
View Post
  • Code

English Learning – Food Related

  • Brandon
  • August 31, 2023

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Fullstar

Input your search keywords and press Enter.