Linux下如何用Python的Subprocess.Popen()启动独立终端运行脚本
让两个Bash脚本在独立终端窗口运行的Python解决方案
问题根源
你的代码直接调用bash执行脚本,默认会在当前Python进程的终端中运行;加上wait()会阻塞Python进程,等第一个脚本执行完才启动第二个,既无法实现独立终端,也做不到并行运行。
解决方案:调用终端程序执行脚本
要让脚本在独立终端窗口运行,需要调用系统的终端应用程序,由终端来启动Bash脚本。不同操作系统/桌面环境的终端命令不同,以下是常见场景的实现:
1. Linux桌面环境
GNOME Terminal(Ubuntu、Fedora等GNOME桌面)
import subprocess # 启动第一个脚本的独立终端 subprocess.Popen(["gnome-terminal", "--", "bash", "-c", "./file1.sh; exec bash"]) # 启动第二个脚本的独立终端 subprocess.Popen(["gnome-terminal", "--", "bash", "-c", "./file2.sh; exec bash"])
--用于分隔终端参数和要执行的命令exec bash可选:脚本执行完成后保持终端窗口不关闭,方便查看输出;不需要的话可以去掉
Konsole(KDE桌面)
import subprocess subprocess.Popen(["konsole", "-e", "bash", "-c", "./file1.sh; exec bash"]) subprocess.Popen(["konsole", "-e", "bash", "-c", "./file2.sh; exec bash"])
2. macOS
方式1:直接调用Terminal.app
import subprocess import os # 确保脚本在当前工作目录执行 script1_path = os.path.abspath("./file1.sh") script2_path = os.path.abspath("./file2.sh") subprocess.Popen(["open", "-a", "Terminal.app", script1_path]) subprocess.Popen(["open", "-a", "Terminal.app", script2_path])
方式2:保持终端窗口不关闭(用osascript)
如果希望脚本执行完后终端不关闭,可以用AppleScript控制:
import subprocess import os current_dir = os.getcwd() # 启动第一个脚本 subprocess.Popen([ "osascript", "-e", f'tell application "Terminal" to do script "cd {current_dir}; ./file1.sh; exec bash"' ]) # 启动第二个脚本 subprocess.Popen([ "osascript", "-e", f'tell application "Terminal" to do script "cd {current_dir}; ./file2.sh; exec bash"' ])
3. Windows
用CMD终端
import subprocess # /k 参数确保脚本执行完后CMD窗口不关闭 subprocess.Popen(["start", "cmd", "/k", "bash file1.sh"], shell=True) subprocess.Popen(["start", "cmd", "/k", "bash file2.sh"], shell=True)
用PowerShell
import subprocess # -NoExit 参数确保脚本执行完后PowerShell窗口不关闭 subprocess.Popen(["start", "powershell", "-NoExit", "-Command", "bash file1.sh"], shell=True) subprocess.Popen(["start", "powershell", "-NoExit", "-Command", "bash file2.sh"], shell=True)
关键注意事项
- 移除
wait():wait()会阻塞Python进程,导致第二个终端必须等第一个脚本执行完才启动,违背了"独立运行"的需求 - 使用绝对路径:建议用
os.path.abspath()获取脚本的绝对路径,避免终端找不到脚本文件 - 终端窗口保留:上述示例中的
exec bash、/k、-NoExit都是为了让终端在脚本执行后不关闭;如果不需要保留窗口,直接去掉这些参数即可
内容的提问来源于stack exchange,提问作者William Addison
相关产品推荐
相关产品推荐

