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

2023-09-02Python开发问题
4

本文介绍了使用 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 窗口中显示输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10