python同时执行多个py脚本
时间: 2024-01-05 13:02:01 浏览: 29
可以使用多线程或多进程来同时执行多个Python脚本。以下是两种方法的示例:
1. 使用多线程
```python
import threading
def run_script(script_name):
# 执行脚本
exec(open(script_name).read())
# 脚本列表
scripts = ['script1.py', 'script2.py', 'script3.py']
# 创建线程列表
threads = []
for script in scripts:
thread = threading.Thread(target=run_script, args=(script,))
threads.append(thread)
# 启动线程
for thread in threads:
thread.start()
# 等待线程结束
for thread in threads:
thread.join()
```
2. 使用多进程
```python
import multiprocessing
def run_script(script_name):
# 执行脚本
exec(open(script_name).read())
# 脚本列表
scripts = ['script1.py', 'script2.py', 'script3.py']
# 创建进程列表
processes = []
for script in scripts:
process = multiprocessing.Process(target=run_script, args=(script,))
processes.append(process)
# 启动进程
for process in processes:
process.start()
# 等待进程结束
for process in processes:
process.join()
```
注意,多线程和多进程都会占用更多的系统资源,需要根据实际情况选择适合的方法。同时,多个脚本之间可能会产生竞争条件,需要注意线程或进程间的同步和互斥。