如何使用 python 在多个终端窗口中运行多个文件

2022-01-18 00:00:00 python subprocess

问题描述

from subprocess import call
call(["python3", "/home/johngr/psdirc/TestBot1.py"]) and call(["python3", "/home/johngr/psdirc/TestBot2.py"]) and call(["python3", "/home/johngr/psdirc/TestBot3.py"])

调用正常,但它只运行第一个文件.我希望它们都在自己的终端窗口中运行.

The call is working but it only runs the first file. I want them all to run in their own terminal windows.


解决方案

不要使用一个接一个地运行:

Don't use and just run one after the other:

call(["python3", "/home/johngr/psdirc/TestBot1.py"])
call(["python3", "/home/johngr/psdirc/TestBot2.py"])
call(["python3", "/home/johngr/psdirc/TestBot3.py"])

如果您不希望他们在开始下一次使用 Popen 之前等待进程完成:

If you don't want them to wait for the process to finish before starting the next use Popen:

 Popen(["python3", "/home/johngr/psdirc/TestBot1.py"])
 Popen(["python3", "/home/johngr/psdirc/TestBot2.py"])
 Popen(["python3", "/home/johngr/psdirc/TestBot3.py"])

call 将 运行 args 描述的命令.等待命令完成,然后返回 returncode 属性. Popen 不会等待.

如果您想确保每个进程以非零退出状态退出,请使用 check_call 对于任何非零退出状态都会引发 CalledProcessError.

If you want to be sure each process exits with a non-zero exit status use check_call which will raise a CalledProcessError for any non-zero exit status.

要为每个终端打开一个终端,您可以使用 gnome-terminal-e 在终端内执行此选项的参数:

To open a terminal for each you can use gnome-terminal with -e Execute the argument to this option inside the terminal:

call(['gnome-terminal', '-e', "python3 /home/johngr/psdirc/TestBot1.py"])
call(['gnome-terminal', '-e', "python3 /home/johngr/psdirc/TestBot2.py"])
call(['gnome-terminal', '-e', "python3 /home/johngr/psdirc/TestBot3.py"])

如果你想打开标签,你可以使用 --tab -e:

If you want to open tabs you can use --tab -e:

cmd =['gnome-terminal', '--tab', '-e', 'python3 /home/johngr/psdirc/TestBot1.py',
      '--tab', '-e','python3 /home/johngr/psdirc/TestBot2.py','--tab', '-e', 
      'python 3 /home/johngr/psdirc/TestBot3.py']
call(cmd)

您似乎没有 gnome-terminal 所以只需将其替换为 lxterminal:

You don't seem to have gnome-terminal so just replace it with lxterminal:

call(['lxterminal', '-e', 'python3 /home/johngr/psdirc/TestBot1.py'])

不确定是否支持 --tab 选项,我在文档中没有看到对它的任何引用.

Not sure if --tab option is supported or not, I don't see any reference to it in the documentation.

相关文章