thinkphp6.0将数据传入py文件中执行

123 阅读1分钟

thinkphp6.0调用py文件

第一步:在项目目录下创建python文件夹

  1. 文件夹存放的python文件

image.png

第二步:在controller中的api文件夹中创建Python.php文件

image.png

<?php

namespace app\data\controller\api;

use app\api\controller\ApiBase;
use app\data\service\myService;
use app\data\service\pythonService;
use think\App;

class Python extends ApiBase
{
    public function __construct(App $app, pythonService $service)
    {
        parent::__construct($app);
        $this->service = $service;
    }
    public function getPython()
    {
        $m = new myService(); //创建一个名为 $m 的新对象,并实例化了一个名为 myService 的类
        $saveData = $m -> save(); //调用 $m 对象的 save() 方法
        $res   = $this->service->getPython($saveData);// 调用 $this->service 对象执行getPython(获取save返回的数据) 
        $this->show($res);
    }
}

第三步:编写myService.php文件

class myService
{
    // 保存推送过来的数据
    public function save(array $data = [])
    {
        //模拟推送过来的数据
        $data = [
            'id' => "20",
            'name' => "羊村守护者",
            'pwd' => "b24a6007b26e04bf8f4b1a914b1a322f91ddd9df",
            'gander' => "男",
            'email' => "shouhuzhe@163.com",
        ];
        $value = $data ?? '';
        $value = $value ? json_decode($value, true) : [];//进行 JSON 解码,返回一个关联数组
        return $value;//返回推送过来的数据
    }

第四步:编写PythonService.php文件

<?php

namespace app\data\service;

use app\data\dao\PythonDao;
use service\BaseService;

class pythonService extends BaseService {

    public function __construct(PythonDao $dao)
    {
        $this->dao = $dao;
    }

    public function getPython(array $array)
    {
        $param = [[
            'id' => $array['id'],
            'name' => $array['name'],
            'pwd' => "$array['pwd'],
            'gander' => $array['gander'],
            'email' => $array['email']],
        ]];

        $file = fopen('D:/qingxin/qingxin-yun/qingxin-yun-houduan/tcair-php/python/dataFL.csv', 'w'); // 打开 CSV 文件以供写入

        foreach ($param as $row) { // 遍历数据数组
            fputcsv($file, $row); // 将每一行数据写入 CSV 文件
        }

        fclose($file); // 关闭 CSV 文件
        $command = escapeshellcmd('python  D:/qingxin/qingxin-yun/qingxin-yun-houduan/tcair-php/python/FL.py');//执行python文件
        //print_r($command);
        $output = shell_exec($command);获取python文件执行结果
        return $output;
    }
}