[英]How to open multiple terminals and execute command in each terminal then save the output from each terminal to a one variable or a file
我有一个项目需要此代码(python 语言),它打开多个终端(linux),然后它在每个终端中执行命令,并将每个终端的 output 存储在一个文件(.txt 或任何其他文件)或一个变量[列表]中。 .
我已经尝试使用 gnome-terminal 进行子进程。代码仅打开终端执行命令,但以状态 1 关闭,并且无法记录每个终端的 output。
for item in d:
sp.getoutput("gnome-terminal -- " + item )
其中 d 是命令列表。
此代码将打开三个终端,在每个终端执行两条命令,并将所有终端的 output 存储在一个日志文件中。 需要注意的一些重要事项:
exec bash
命令,以在命令完成后保持每个终端打开。tee
命令中包含 append 标志 ( -a
),因此脚本将覆盖任何现有的日志文件。2>&1
来捕获 output 和日志中的错误,如第二个命令字符串所示。注意- 在 Ubuntu 20.04 中测试,使用 Python 3.8。
import subprocess
import shlex
import time
my_log = "my.log"
commands = (
# Open a new tab and display time and message
"gnome-terminal --tab -- bash -c \"date 2>&1 | tee " + my_log +
"; echo foo 2>&1 | tee -a " + my_log + "; exec bash\"",
# Open a new tab and display time and an error message
"gnome-terminal --tab -- bash -c \"date 2>&1 | tee -a " + my_log +
"; whatami 2>&1 | tee -a " + my_log + "; exec bash\"",
# Open a new tab and display time and the current user
"gnome-terminal --tab -- bash -c \"date 2>&1 | tee -a " + my_log +
"; whoami 2>&1 | tee -a " + my_log + "; exec bash\"",
# Display command results from log
"cat my.log",)
for c in commands:
subprocess.run(shlex.split(c))
time.sleep(0.5)
Output:三个新终端,初始终端中my.log
的内容:
Mon 03 Jan 2022 03:16:54 PM EST
foo
Mon 03 Jan 2022 03:16:55 PM EST
bash: whatami: command not found
Mon 03 Jan 2022 03:16:56 PM EST
stack
顺便说一句,我对你的用例很感兴趣; 你能和我们分享吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.