python动态执行py文件

通过os模块执行

import os
os.system("python main.py")

多线程

import threading
import os
threading.Thread(target=os.system, args=("python main.py",)).start()

多进程

from multiprocessing import Process
import os
Process(target=os.system, args=("python main.py",)).start()

通过exec执行


# 执行文件
from multiprocessing import Process
import threading

def exec_file(file_name, func_name):
    with open(file_name, "rb") as f:
        source_code = f.read()
    exec_code = compile(source_code, file_name, "exec")
    scope = {}
    exec(exec_code, scope)
    f = scope.get(func_name, None)
    f() #如果是函数则执行,类则初始化

if __name__ == "__main__":
	exec_file("main.py", "main")
	# 多线程
	# threading.Thread(target=exec_file, args=("main.py", "main")).start()
	# 多进程
	# Process(target=exec_file, args=("main.py", "main")).start()

结合sched定时模块,定时执行

from multiprocessing import Process
import threading
import sched
import time
import os

# 生成调度器
schedule = sched.scheduler(time.time, time.sleep)

# 执行文件
def exec_file(file_name, func_name):
    with open(file_name, "rb") as f:
        source_code = f.read()
    exec_code = compile(source_code, file_name, "exec")
    scope = {}
    exec(exec_code, scope)
    f = scope.get(func_name, None)
    f()

def checkedition(inc=3600):
    print("start")
    # Process(target=exec_file, args=("main.py", "main")).start()
    Process(target=os.system, args=("python main.py",)).start()
    schedule.enter(inc, 0, checkedition, (inc,))

def main(inc=3600):
    # enter四个参数分别为:间隔事件、优先级(用于同时间到达的两个事件同时执行时定序)、被调用触发的函数,
    # 给该触发函数的参数(tuple形式)
    schedule.enter(0, 0, checkedition, (inc,))
    schedule.run()

if __name__ == "__main__":
    main(60)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

图像处理大大大大大牛啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值