Python’s built-in raw_input() function is a quick and dirty way to get text input from the user in your Python command line application. But it’s really only optimal for a very small input string. Also, it can’t provide a default value that the user can then edit. For more substantial input, many Linux tools use your $EDITOR environment variable to launch a visual editor, potentially with default text.
Some example are git commit messages, and
crontab -e. A typical workflow is as follows:
- User runs a command like
- Git creates a temp file with a default commit template
- Vim, emacs or nano opens the temp file
- User edits the text
- User saves and quits
- Git reads in the new contents of the temp file, and deletes it
After some research, I came up with the following helper to do just that in Python:
Using less as a pager
With that turning out nicely, I decided to also try to copy git’s pager. When you run a command like
git log that can produce thousands of lines of text, it passes the content through
less, which breaks it into scrollable pages. If you abstract your print statements into a logger or a custom function, you can easily enable/disable the pager.
Finally, adding some color to your console text is easy with the termcolor library.