【问题标题】:Show curses GUI for a script, even with redirected output显示脚本的 curses GUI,即使是重定向输出
【发布时间】:2020-05-14 19:04:02
【问题描述】:

我想写一个类似终端版本的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),但 curses UI 显示在 /dev/pts/1 中。
所以我的问题是,有没有办法将 curses 输出重定向回 /dev/tty,或者是否有不同的方式来显示基于文本的 GUI,可以通过更改 sys.stdout 来重定向?

【问题讨论】:

    标签: python linux bash curses output-redirect


    【解决方案1】:

    我通过为我的 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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多