即使输出重定向,也显示脚本的诅咒GUI

问题描述 投票:0回答:1

我想编写类似dmenu的终端版本的文件,该文件可用于搜索文件,然后将文件的位置传递给管道中的另一个程序,例如:

my_script | xargs vim # search for a file and open in vim

我尝试使用输出重定向在python中完成此操作,但似乎不适用于curses。

import sys
import curses

prev_out = sys.stdout
print("1:", sys.stdout)
sys.stdout = open("/dev/tty", "w")
print("2:", sys.stdout)

window = curses.initscr()
window.addstr(1, 1, "testing")
window.getch()
curses.endwin()

sys.stdout = prev_out
print("3:", sys.stdout)

当我这样称呼它时:

myscript > /dev/pts/1 # redirect output to another tty

print的行为符合我的期望(原始tty中为2,其他tty中为1和3),但是curses UI显示在/ dev / pts / 1中。所以我的问题是,是否有办法将curses输出重定向回/ dev / tty,还是有其他方法来显示基于文本的GUI,可以通过更改sys.stdout来进行重定向?

python linux bash curses output-redirect
1个回答
0
投票

我通过为我的python脚本编写一个简短的bash包装器来实现此行为。

#!/bin/bash
# bash wrapper, that handles forking output between
# GUI and the output meant to go further down the pipe

# a pipe is created to catch the the wanted output
# date and username added in case of two scripts running at
# approximately the same time
fifo=/tmp/search_gui_pipe-$(whoami)-$(date +%H-%M-%S-%N)
[ ! -p "$fifo" ] && mkfifo $fifo

# python script is called in background, with stdin/out
# redirected to current tty, and location of the pipe file
# passed as an argument (also pass all args for parsing)
./search_gui.py "$fifo" $@ >/dev/tty </dev/tty &

# write the program output to stdout and remove the pipe file
cat "$fifo" && rm "$fifo"
© www.soinside.com 2019 - 2024. All rights reserved.