为脚本显示 curses GUI,即使有重定向的输出
Show curses GUI for a script, even with redirected output
我想写一个类似于终端版本的 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,另一个中为 1 和 3),但诅咒 UI 显示在 /dev/pts/1.
所以我的问题是,有没有办法将 curses 输出重定向回 /dev/tty,或者是否有不同的方法来显示基于文本的 GUI,可以通过更改 sys.stdout 来重定向?
我通过为我的 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"
我想写一个类似于终端版本的 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,另一个中为 1 和 3),但诅咒 UI 显示在 /dev/pts/1.
所以我的问题是,有没有办法将 curses 输出重定向回 /dev/tty,或者是否有不同的方法来显示基于文本的 GUI,可以通过更改 sys.stdout 来重定向?
我通过为我的 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"