Python 脚本打开多终端并运行多个代码

import subprocess import platform import os  # 定义要运行的.py文件列表 python_scripts = ["./detect_alltime.py", "./detect_alltime.py", "./detect_alltime.py"] # E:\ultralytics-predictort\detect_alltime.py # 根据操作系统确定打开终端的命令 if platform.system() == "Windows":     terminal_cmd = "start cmd /K python" else:     terminal_cmd = "gnome-terminal -- bash -c 'python3"  # 启动多个终端并运行脚本 # 启动多个终端并运行.py文件 for script in python_scripts:     script_path = os.path.abspath(script)     subprocess.Popen(f"{terminal_cmd} {script_path}", shell=True)  # 保持主程序运行,以便终端会话保持打开状态 input("Press Enter to exit...")

请注意,上述代码假设你的操作系统是Windows、Linux或macOS,并且使用的是默认的终端程序。如果你使用的是不同的操作系统或终端程序,请相应地修改terminal_command的值。

另外,确保脚本文件(如script1.py、script2.py)位于与此Python程序相同的目录中,或者提供完整的文件路径。这将确保脚本能够被正确地启动和执行。

import subprocess
import platform
import os

# 要运行的.py文件列表
python_scripts = ["script1.py", "script2.py", "script3.py"]

# 根据操作系统确定启动终端的命令
if platform.system() == "Windows":
    terminal_command = "start cmd /K python"
elif platform.system() == "Linux" or platform.system() == "Darwin":  # Linux 或 macOS
    terminal_command = "gnome-terminal -x bash -c 'python3"
else:
    raise Exception("不支持的操作系统")

# 启动多个终端并运行.py文件
for script in python_scripts:
    script_path = os.path.abspath(script)
    subprocess.Popen(f"{terminal_command} {script_path}", shell=True)

猜你喜欢

转载自blog.csdn.net/moonlightpeng/article/details/132720192
今日推荐