Using Python#39;s Subprocess to Display Output in New Xterm Window(使用 Python 的子进程在新的 Xterm 窗口中显示输出)
问题描述
我正在尝试从同一个 Python 脚本在两个终端中输出不同的信息(很像 这个家伙).我的研究似乎指向的方式是使用 subprocess.Popen 打开一个新的 xterm 窗口并运行 cat 以在窗口中显示终端的标准输入.然后我会将必要的信息写入子进程的标准输入,如下所示:
I am trying to output different information in two terminals from the same Python script (much like this fellow). The way that my research has seemed to point to is to open a new xterm window using subprocess.Popen and running cat to display the stdin of the terminal in the window. I would then write the necessary information to the stdin of the subprocess like so:
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 方法只返回字符串的长度,然后继续.我不确定对子流程和管道的工作方式是否存在误解,但如果有人可以帮助我,将不胜感激.谢谢.
The string "Information" would then display in the new xterm. However, this is not the case. The xterm does not display anything and the stdin.write method simply returns the length of the string and then moves on. I'm not sure is there is a misunderstanding of the way that subprocess and pipes work, but if anyone could help me it would be much appreciated. Thanks.
推荐答案
这不起作用,因为您将内容传递给 xterm 本身,而不是在 xterm 中运行的程序.考虑使用命名管道:
This doesn't work because you pipe stuff to xterm itself not the program running inside xterm. Consider using named pipes:
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!
")
time.sleep(1)
这篇关于使用 Python 的子进程在新的 Xterm 窗口中显示输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Python 的子进程在新的 Xterm 窗口中显示输出
基础教程推荐
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
