How to build interactive menu for command-line app

2019-04-08 19:12发布

I've been working with click to make a command line program. Right now I'm implementing interactive menus in a very textual way. for example:

1-option #1
2-option #2
Enter the index of the option you want to select: 

But I would love to do this in a more elegant and interactive way. For example, I love the way Yeoman implements its menus. Here is the menu in action. enter image description here

Is there any python library that let's us build command line menus like this? I have looked at libraries like curses, cmd etc. But they seem to give you a whole separate window to manage and look kind of unpythonic.

1条回答
贪生不怕死
2楼-- · 2019-04-08 19:21

curses, or something like it, really is what you want.

While curses can be used to pop up "windows" with borders around them, erase the whole window, etc., at its base, what it's about is giving you control over your terminal window—moving a cursor around, highlighting text, all the other things you're trying to do.

Some of the higher-level libraries that make things easier (like urwid) do push you toward a more specific look & feel that may not be what you're after, but curses can easily be used for exactly what you're trying to build.

The only real problem with curses it's that it's not ubiquitous. Almost all *nix platforms will have it, but Windows won't. But the answer there isn't much different—there are curses-faking libraries, or Windows-specific conio libraries (including a limited one in the stdlib, inside mscvrt).

查看更多
登录 后发表回答