我正在使用subprocess.popen使用给定的python文件生成多个CMD。最后都带有input()。问题是,如果代码中有任何引发的异常,则窗口只是关闭而我看不到发生了什么。

无论错误如何,我都希望它保持打开状态。这样我就可以看到或因为此脚本无法运行而使错误返回主窗口。

我在Windows上运行它:

import sys
import platform
from subprocess import Popen,PIPE

pipelines = [("Name1","path1"),
         ("Name2","path2")]

# define a command that starts new terminal
if platform.system() == "Windows":
  new_window_command = "cmd.exe /c start".split()
else:  #XXX this can be made more portable
  new_window_command = "x-terminal-emulator -e".split()
processes = []
for i in range(len(pipelines)):
  # open new consoles, display messages
  echo = [sys.executable, "-c",
        "import sys; print(sys.argv[1]);  from {} import {}; obj = {}(); obj.run();  input('Press Enter..')".format(pipelines[i][1],pipelines[i][0],pipelines[i][0])]
  processes.append(Popen(new_window_command + echo + [pipelines[i][0]]))

for proc in processes:
  proc.wait()

最佳答案

要查看错误,请尝试将所需的代码片段包装在try/except

try:
    ...
except Exception as e:
    print(e)

07-27 16:55