我试图从同一个Python脚本在两个终端中输出不同的信息(很像这个家伙)。我的研究似乎指出的方式是使用 subprocess.Popen 打开一个新的 xterm 窗口并运行 cat 以在窗口中显示终端的标准输入。然后,我会将必要的信息写入子进程的标准输入,如下所示:
from subprocess import Popen, PIPE
terminal = Popen(['xterm', '-e', 'cat'], stdin=PIPE) #Or cat > /dev/null
terminal.stdin.write("Information".encode())
字符串“Information”将显示在新的 xterm 中。然而,这种情况并非如此。 xterm 不显示任何内容,stdin.write 方法只是返回字符串的长度,然后继续。我不确定子进程和管道的工作方式是否存在误解,但如果有人可以帮助我,我将不胜感激。谢谢。
这不起作用,因为您将内容通过管道传输到
xterm
本身,而不是在 xterm
内部运行的程序。考虑使用命名管道:
import os
from subprocess import Popen, PIPE
import time
PIPE_PATH = "/tmp/my_pipe"
if not os.path.exists(PIPE_PATH):
os.mkfifo(PIPE_PATH)
Popen(['xterm', '-e', 'tail -f %s' % PIPE_PATH])
for _ in range(5):
with open(PIPE_PATH, "w") as p:
p.write("Hello world!\n")
time.sleep(1)