Laravel 中运行 Python 脚本

Laravel框架
481
0
0
2022-09-07

使用 Python 脚本创建一个文件

#!/usr/bin/python
#-*-conding-*-
#创建文件,并写入数据:要求不能与现存系统文件重名

import os

def makefile(path,content):
    if os.path.exists(path):
        if os.path.isdir(path):
            f = open('hello world.txt','w+')
            f.write(content)
            f.seek(0)
            read = f.readline()
            f.close()
            print(read)
        else:
            print('please input the dir name')
    else:
        print('the path is not exists')


path = "C:"
content = "hello world"
makefile(path,content)

Laravel 中可以使用路由调用

//routes.php

use Symfony\Component\Process\Process;

Route::get('python', function(){

    $process = Process::fromShellCommandline('python C:\test.py'); // CLI 命令

    $process->run();

    if (!$process->isSuccessful()) {
        throw new ProcessFailedException($process);
    }

    // 获取脚本输出  
    return $process->getOutput();
});

其实这里跟 Laravel 框架没有什么关系,使用的是 Symfony\Component\Process\Process 这个依赖包,可以运行各种 CLI 的命令,这里只是抛砖引玉。

具体可以查看 Symfony的文档