python动态执行py文件
程序员文章站
2022-05-14 18:48:44
...
通过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)
上一篇: 血压低食疗方法有哪些