Creating a curses app that interacts with the terminal, yet reads from stdin?

Tim Chase python.list at tim.thechases.com
Sat Apr 18 20:47:32 EDT 2020


I know that vim lets me do things like

 $ ls | vim -

where it will read the data from stdin, but then take over the screen
TUI curses-style, and interact directly with the keyboard input
without being limited to input from stdin.

I've played around with something like

    import sys
    import curses
    d = list(sys.stdin) # read/process/store it
    def main(stdscr):
        stdscr.clear()
        for i, s in enumerate(d):
            stdscr.addstr(i, 1, s.strip())
        stdscr.refresh()
        stdscr.getkey()
    curses.wrapper(main)

but it complains when I run it with

  $ seq 10 | python myprog.py
  ...
  _curses.error: no input

I've tried adding (after the imports)

    tty = open('/dev/tty', 'r+b')
    curses.setupterm(fd=tty.fileno())

to coerce it, but it doesn't seem to do anything fruitful.

Any advice for how to go about replicating this vim-like behavior in
Python?

Thanks!

-tkc






More information about the Python-list mailing list