4

Automatic registration and ldquo; orders & rdquo; for a Python Command Line...

 3 years ago
source link: https://www.codesd.com/item/automatic-registration-and-ldquo-orders-for-a-python-command-line-program.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Automatic registration and ldquo; orders & rdquo; for a Python Command Line Program

advertisements

I would like to develop a command-line program that can process and give "help" for subcommands. To be concrete, say I have a single script called "cgent" and I would like to have subcommands "abc", "def", and "xyz" execute and accept the rest of the sys.args for processing by optparse.

cgent abc [options]
cgent help abc
....

All of this is straightforward if I hard-code the subcommand names. However, I would like to be able to continue to add subcommands by adding a class or module (?). This is similar to the idea that is used by web frameworks for adding controllers, for example. I have tried digging through pylons to see if I can recreate what is done there, but I have not unravelled the logic. Any suggestions on how to do this?

Thanks, Sean


You'll have to create a "command registry". This can be as simple as a dictionary.

In the main program you do:

commands = {}

And in any submodules you add you do

from yourmodule.main import commands

def mynewcommand(arguments=here):
    pass

commands['newcommand'] = mynewcommand

Then you can use argparse to handle the commands. In which case your module needs to add the subparser part for the command too.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK