Skip to content
Browse files

Cleanup, bit of refactoring.

  • Loading branch information...
1 parent 18503df commit 6adf16a111893712c2af7f8274bdeb28ba9f5eb5 Andrey Petrov committed Jun 4, 2009
Showing with 30 additions and 15 deletions.
  1. +30 −15 grope.py
View
45 grope.py
@@ -37,7 +37,7 @@
"""
__author__ = "David Warde-Farley <http://www.cs.toronto.edu/~dwf/>"
-__contributors__ = ["Andrey Petrov <http://www.shazow.net/>"]
+__contributors__ = ["Andrey Petrov <http://shazow.net/>"]
import fileinput, curses, tempfile, os, sys, subprocess
@@ -140,14 +140,16 @@ def cleanup(stdscr):
curses.echo()
curses.endwin()
-def main(stdscr, lines):
- """Main loop, called by curses.wrapper() to squelch any errors."""
+def get_selected_line(stdscr, lines):
+ """Called by curses.wrapper, renders the interface and fetches the selected line."""
init(stdscr)
state = ProgramState(stdscr, lines)
+
while True:
c = stdscr.getch()
-
+
if c == ord('q') or c == ord('Q'):
+ # Quit
break
elif c == curses.KEY_DOWN:
@@ -163,37 +165,50 @@ def main(stdscr, lines):
except curses.error:
curses.beep()
state.refresh()
-
+
elif c == ord('\n'):
+ # Enter
break
+
cleanup(stdscr)
- print "You selected line %d: %s" % (state.selected_line,
- state.text[state.selected_line])
-
-if __name__ == "__main__":
+ print state.text[state.selected_line]
+
+def main():
lines = []
for line in fileinput.input():
lines.append(line)
-
+
if len(sys.argv[1:]) == 0 or '-' in sys.argv[1:]:
+ """
+ This is a hack to get the STDIN input while also keeping the keyboard
+ input going for the curses UI.
+
+ It works by spawning a subprocess which writes the STDIN to a temporary
+ file, this frees up the main process to read the keyboard commands via
+ STDIN.
+ """
# Create a temporary file.
filedes, fname = tempfile.mkstemp(prefix='.grope.')
filehandle = os.fdopen(filedes, 'w')
filehandle.writelines(lines)
filehandle.close()
-
+
# This of course breaks on Windows, which Andrey insists is a feature.
realstdin = open('/dev/tty', 'r')
-
+
# TODO: Robust way to get the current Python interpreter/path to script
args = ['python', sys.argv[0], fname]
-
+
# Fork a subprocess that can talk to the real keyboard
returncode = subprocess.call(args, stdin=realstdin)
-
+
# Clean up our temporary file.
os.remove(fname)
sys.exit(returncode)
+
else:
- curses.wrapper(main, lines)
+ r = curses.wrapper(get_selected_line, lines)
+
+if __name__ == "__main__":
+ main()

0 comments on commit 6adf16a

Please sign in to comment.
Something went wrong with that request. Please try again.