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

Using Python#39;s Subprocess to Display Output in New Xterm Window(使用 Python 的子进程在新的 Xterm 窗口中显示输出)
本文介绍了使用 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 窗口中显示输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)