7
votes

I want to develop a small Python app that interacts with the user via the console/command line. Are there any good libraries I can use to get user input and display the output in a nice-looking way? I tried searching but most of what I found was command-line argument processing, didn't see anything about user interaction in the shell.

It should be crossplatform (Windows and Linux)

3
Take a look at this article While this uses 'import optparse', they say the current version is 'import argparse' this is not correct. Stick to optparse. I am also looking at 'import cli' Stay tuned... Flint - user2215595
To clarify, @rdodev is NOT asking for a CLI library, but a terminal GUI library (i.e., curses). No doubt others will be led here only to find the completely wrong thing. - darkfeline

3 Answers

6
votes

You can control the Unix terminal with the curses library. The library essentially lets you build a simple terminal GUI.

If you need more, take a look at Urwid as well. Urwid offers more complex GUI widgets for the discerning terminal GUI developer. :-)

10
votes

A really excellent library is cmd which is part of the python standard library. It is cross platform Windows, Linux, Mac. You just have to implement one class and it offers so many great features:

  1. provides list of supported commands(they end up being implemented as methods)
  2. help command that can be called to explain one of your commands
  3. handles the whole entering a command, checking syntax, and calling your method command loop cycle.
  4. users can save the commands they have run in an interactive session and run them as a script. check out the example below.

If you take the turtle shell example and save it as turtleshell.py and save the below turtle script file as circles.txt

circle 20
circle 50
circle 100
bye

then you could run the turtle script with the following command:

cat circles.txt | ./turtleshell.py

so in the simple example shown in the docs the developer has essentially made a simple mini-language that can be used as an easier interface to to the turtle module making it even easier to introduce programming to kids. The examples above have been taken from the python3 docs because they have included a detailed example in their docs which wasn't there in the 2.7 docs, but cmd is available and fully functional in python 2.3 and later.

2
votes

Curses is the most widely used in the Unix environment according to the doc. For Windows you could look at Windows Console Driver, WConio - Windows CONsole I/O for Python or Wcurses. I couldn't find much on cross platform console libraries unfortuntaly.

If your Windows users are CLI users they probably have cygwin which has ncurse support so curses is still the best option if you ask me.