thinkphp6.0调用py文件
第一步:在项目目录下创建python文件夹
- 文件夹存放的python文件

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

<?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();
$saveData = $m -> save();
$res = $this->service->getPython($saveData);
$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) : [];
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;
}
}