python diango后端支持运行脚本+vue前端支持脚本运行

公子Learningcarer / 2024-01-10 / 原文

# 使用Python内置的subprocess模块来执行Python脚本

# 使用注意:
    # 1,依赖包需要提前导入至脚本中
    # 2,script_path变量是脚本得绝对路径
    # 3,filename变量是脚本得名称
    
# 搭配vue页面使用
    # 想法:页面支持导入,编辑,执行脚本
        # 导入:默认指定路径下,需要填写脚本文件得名称
        # 编辑:编辑完成后,点击保存,覆盖原有文件
        # 保存:将脚本得名称,绝对路径保存至数据库,保存完成后,执行按钮高亮
        # 执行:点击执行,调用后端api运行接口,页面需要传输(绝对路径 + 脚本名称),结果返回页面
        # 批量执行:生成list集合(脚本id)(数据库查询所得),点击执行按照list索引顺序依次执行
        
    # 数据库字段:
        # id:自增
        # script_name:脚本名称
        # script_path:脚本绝对路径
        # result: 最新运行结果
        # create_time: 创建时间
        # updata_time: 更新时间

 

 

两种方式
第一种:文件形式


import subprocess

def execute_python_script(script_path: str, filename: str):
    # 执行Python脚本
    result = subprocess.run(['python', script_path + filename], stdout=subprocess.PIPE)
    # 处理输出结果
    output = result.stdout.decode('utf-8')
    print(output)

# 调用方法
# script_path为脚本路径,filename为脚本名称
execute_python_script(
    script_path=r'G:\pycharmDl\job\marketingscriptcase\练习执行python脚本'+'\\',
    filename='script_py.py')
# 结果
('我的年龄是32', '{"age": 32}')

第二种:字符串方式

import json, unittest


def execute_script(script_str):
    try:
        exec(script_str)
    except Exception as e:
        print(f"执行脚本时发生错误: {e}")


script = """  
import json  

class Name:  
    def __init__(self, age):  
        self.age = age  

    def ages(self):  
        my = {'age': self.age}  
        return '我的年龄是' + str(self.age), json.dumps(my)  

if __name__ == '__main__':  
    print(Name(32).ages())  
"""
script1 = """  
import unittest
class MyTestCase(unittest.TestCase):
    def setUp(self):
        pass
    def tearDown(self):
        pass
    def test01(self):
        return 'test01'
    def test02(self):
        return 'test02'

if __name__ == '__main__':
    print(unittest.main())

"""
execute_script(script)
execute_script(script1)
# 结果
('我的年龄是32', '{"age": 32}')

 脚本

import json


class Name:
    def __init__(self, age):
        self.age = age

    def ages(self):
        my = {'age': self.age}
        return '我的年龄是' + str(self.age), json.dumps(my)


if __name__ == '__main__':
    print(Name(32).ages())