是否可以为终端窗口指定一个唯一的名称来通过python运行命令?

我必须通过Python中的os.system()运行终端代码。 两个命令应分别在两个端子中运行。 是否可以为终端窗口指定唯一的名称/ ID以在其指定的终端窗口中运行每个命令?

您打开的每个终端都会在/dev/pts/获得一个唯一编号的文件(确切地说是伪终端从属(PTS)设备),可以识别和寻址它。 要获取终端窗口的相应文件名,您可以使用例如tty (请参阅此答案以获取替代方案;阅读man pts了解更多信息):

 $ tty /dev/pts/4 

例如,您可以使用此文件名将输出重定向到不同的终端窗口,如下所示:

 $ echo test >/dev/pts/4 # run anywhere test # printed in terminal window 4 

你不能真正在另一个终端运行命令,因为它不是运行命令的终端,而是通常在终端中运行的shell。 但是,您可以使用以下重定向模拟终端窗口中运行的命令的行为(取自Linux伪终端:执行从另一个终端发送的字符串 ):

 echo test /dev/pts/4 

如果你想显示你运行的命令我也建议编写一个函数( 如何在bash脚本中省略某些输入变量,如$ 1和$ 2时使用$ * ),例如:

 run_in(){ t=/dev/pts/$1 && echo "${*:2}" >$t && eval "${@:2}" <$t &>$t } 

在一行中:

 run_in(){ t=/dev/pts/$1&&echo "${*:2}" >$t&&eval "${@:2}" <$t &>$t;} 

像这样使用它:

 $ run_in 4 echo test # run anywhere $ echo test # printed in terminal window 4 (if prompt was already there) test # printed in terminal window 4 

在这种情况下,唯一未知的是/dev/pts/? Python程序应使用的数字。 获得这些数字的一种可能方法是启动自己的终端窗口,将其“数字”输出到文件中,然后您可以读取它[ 参考 ] 。 假设您正在使用gnome-terminal ,Python代码的相关部分可能如下[ ref ]

 #!/usr/bin/python import os import subprocess os.system("gnome-terminal -x bash -c 'tty > /tmp/my-app-tty-1; exec bash'") my_terminal_1 = subprocess.Popen(["cat", "/tmp/my-app-tty-1"], stdout=subprocess.PIPE).communicate()[0] command = "echo Test on: $(date) >" + my_terminal_1 print my_terminal_1 print command os.system(command) 

如果是Perl脚本[ 参考 ]

 #!/usr/bin/perl os.system("gnome-terminal -x bash -c 'tty > /tmp/my-app-tty-1; exec bash'"); my $my_terminal_1 = `cat /tmp/my-app-tty-1`; my $command = "echo Test on: \$\(date\) > $my_terminal_1"; print ("$my_terminal_1"); print ("$command"); os.system("$command");