使用Python的子进程在新Xterm Wind中显示输出

2024-05-28 19:21:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从同一个Python脚本(非常像this fellow)的两个终端输出不同的信息。我的研究似乎指向了一个新的xterm窗口,使用subprocess.Popen和running cat在窗口中显示终端的stdin。然后我将必要的信息写入子进程的stdin,如下所示:

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方法只返回字符串的长度,然后继续。我不确定对子流程和管道的工作方式是否存在误解,但如果有人能帮助我,将不胜感激。谢谢。


Tags: 字符串脚本信息终端informationstdinthisterminal
1条回答
网友
1楼 · 发布于 2024-05-28 19:21:02

这不起作用,因为您将内容传递给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)

相关问题 更多 >

    热门问题