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

# 使用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}')

文件形式

script.py

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())

第二种:字符串方式(函数方法及脚本字符串)注意:脚本字符串所需得第三方包,需要在文件中引入依赖

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())  
"""

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

 第三种:字符串方式(函数方法及脚本字符串)注意:脚本字符串所需的第三方包,只需要在字符串中引入依赖就可以

import subprocess
import json


def execute_script(script_str):
    # 创建一个子进程来执行脚本
    process = subprocess.Popen(['python', '-c', script_str], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    # 等待脚本执行完成
    stdout, stderr = process.communicate()

    # 打印脚本的输出
    print(stdout.decode('utf-8'))
    print(stderr.decode('utf-8'))

    # 检查脚本是否成功执行
    if process.returncode != 0:
        raise Exception(f"脚本执行失败,返回码: {process.returncode}")


# 脚本字符串
script1 = """    
import unittest  
from time import sleep  

class MyTestCase(unittest.TestCase):  
    def setUp(self):  
        pass  
    def tearDown(self):  
        pass  
    def test01(self):  
        sleep(1)  
        print('test01---')  
    def test02(self):  
        print('test02---')  

if __name__ == '__main__':  
    unittest.main()  
"""
script2 = """
import json
from script_def import name1
class Name:
    def __init__(self, age):
        self.age = age

    def ages(self):
        my = {'age': self.age}
        # 引入函数方法获取返回值
        her = name1(str(11))
        return '我的年龄是' + str(self.age), json.dumps(my)


if __name__ == '__main__':
    print(Name(32).ages())
"""
try:
    result = execute_script(script1)
    result1 = execute_script(script2)
except Exception as e:
    print(f"执行脚本时发生错误: {e}")

# 结果
test01---
test02---
我的年龄偷偷告诉你 11
('我的年龄是32', '{"age": 32}')

其他py文件得函数方法(在第三种方法中使用)


def name1(age):
    print('我的年龄偷偷告诉你',age)
    return age

 

第四张:字符串加请求头方式

import json
from script_def import name1

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


# 脚本字符串
script = """  

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

    def ages(self):  
        my = {'age': self.age}  
        # 引入第三方函数方法并获取返回值
        her = name1(str(11))
        return '我的年龄是' + str(self.age), json.dumps(my), her
if __name__ == '__main__':
    print(Name(32).ages())

"""

# 这是请求方法,可以单独传输赋值,看vue得样例
execute_script(debug_req='Name(32).ages()',script_str=script)

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

其他py文件得函数方法(在第四种方法中使用)

def name1(age):
    return age

vue页面样例

 

posted @ 2024-01-10 10:31  公子Learningcarer  阅读(36)  评论(0编辑  收藏  举报