gpt4 book ai didi

python - 使用 Python 的子进程在新的 Xterm 窗口中显示输出

转载 作者:太空宇宙 更新时间:2023-11-04 01:40:26 27 4
gpt4 key购买 nike

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

最佳答案

这是行不通的,因为您将内容传送到 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)

关于python - 使用 Python 的子进程在新的 Xterm 窗口中显示输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5558720/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com