【问题标题】:Using Python's Subprocess to Display Output in New Xterm Window使用 Python 的子进程在新的 Xterm 窗口中显示输出
【发布时间】:2011-07-30 08:18:00
【问题描述】:

我正在尝试从同一个 Python 脚本(很像 this fellow)在两个终端中输出不同的信息。我的研究似乎指向的方式是使用 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 方法只返回字符串的长度,然后继续。我不确定对子流程和管道的工作方式是否存在误解,但如果有人可以帮助我,将不胜感激。谢谢。

【问题讨论】:

    标签: python pipe subprocess


    【解决方案1】:

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

    【讨论】:

    • 非常感谢。一件事是,当用于在脚本中关闭管道之前更新终端时,我必须将其设为 p = open(PIPE_PATH, 'w', 1)。
    • 如何使用gnome-terminal 代替xterm
    • @shiva 我稍微编辑了答案。使用上面的 sn-p,您可以在 Popen 行中将 xterm 替换为 gnome-terminal。
    • 有windows的解决方案吗? CMD 是 ****,但也许还有一些其他的窗口终端可以打开并通过管道传输到?
    猜你喜欢
    • 1970-01-01
    • 2012-06-15
    • 2018-10-02
    • 2013-06-06
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    相关资源
    最近更新 更多