如何打开多个新Shell并以不同参数运行同一Python脚本?
在新Shell中使用不同参数运行Python脚本
Windows 环境
CMD
使用start命令启动新CMD窗口并执行脚本:
start cmd /k "python your_script.py arg1 arg2"
/k:执行命令后保持窗口打开;若需执行完自动关闭,替换为/c。
PowerShell
通过Start-Process命令创建新PowerShell窗口:
Start-Process powershell -ArgumentList "-NoExit", "-Command", "python your_script.py arg1 arg2"
-NoExit:窗口执行脚本后不关闭;移除该参数则执行完成后自动关闭窗口。
macOS/Linux 环境
macOS
方式一:用open调用终端
open -a Terminal --args "python3 your_script.py arg1 arg2"
方式二:通过AppleScript指定执行命令
osascript -e 'tell application "Terminal" to do script "cd /path/to/script; python3 your_script.py arg1 arg2"'
需替换
/path/to/script为你的脚本实际所在目录
Linux(GNOME Terminal)
gnome-terminal -- bash -c "python3 your_script.py arg1 arg2; exec bash"
exec bash:执行脚本后保持终端窗口打开;移除则窗口自动关闭。
Linux(Konsole/KDE)
konsole -e "bash -c 'python3 your_script.py arg1 arg2; exec bash'"
打开多个新Shell窗口,各用不同参数运行脚本
可以通过批量脚本一次性创建多个窗口,无需手动重复输入命令。
Windows(CMD 批处理脚本)
保存为run_multiple.cmd,双击运行即可:
@echo off start cmd /k "python your_script.py arg1" start cmd /k "python your_script.py arg2" start cmd /k "python your_script.py arg3"
Windows(PowerShell 脚本)
保存为run_multiple.ps1,右键选择PowerShell运行:
$argList = @("arg1", "arg2", "arg3") foreach ($arg in $argList) { Start-Process powershell -ArgumentList "-NoExit", "-Command", "python your_script.py $arg" }
macOS/Linux(Bash 脚本)
保存为run_multiple.sh,添加执行权限后运行:
#!/bin/bash # 替换为你的参数列表 argList=("arg1" "arg2" "arg3") # 替换为脚本所在绝对路径 scriptPath="/path/to/your_script.py" for arg in "${argList[@]}"; do # macOS 版本 osascript -e 'tell application "Terminal" to do script "python3 '$scriptPath' '$arg'"' # Linux GNOME 版本,注释上面一行,解开下面一行 # gnome-terminal -- bash -c "python3 '$scriptPath' '$arg'; exec bash" done
添加执行权限并运行:
chmod +x run_multiple.sh ./run_multiple.sh
注意:如果脚本不在当前工作目录,务必使用绝对路径或在命令中先通过
cd切换到脚本所在目录,避免找不到脚本的问题。
内容的提问来源于stack exchange,提问作者ThomasClouston
相关产品推荐
相关产品推荐

