2

I will do a command line application with plugin capability, each new plugin will be invoked by a sub command from a __main__.py script.

I used to use argparse, I wonder if it's possible with argparse to implement sub command + plugin looking like (I found some tool but using deprecated packages) ?

myfantasticCLI
├── __main__.py
└── plugins
    ├── create.py
    ├── notify.py
    └── test.py

I know that I could use argparse for sub command, but don't know how to use it in a dynamic loading way. :/

Chen Xie
  • 3,849
  • 8
  • 27
  • 46
Ali SAID OMAR
  • 6,404
  • 8
  • 39
  • 56

1 Answers1

1

If you initialize the argparse subparsers with

sp = parser.add_subparsers(dest='cmd',...)

then after parsing args.cmd will be the name of the chosen subparser or command.

Then a simple if tree could import and run the desired modules

cmd = args.cmd
if cmd in ['module1',...]:
   import plugins.module1 as mod:
   mod.run(...)
elif cmd in ['module2',....]:
   import plugins.module2 as mod:
   ...

There are fancier ways of doing this, but I prefer starting with the obvious.

Also my focus is on getting the cmd name from the parser, not on the details of importing a module given the name. You don't need argparse to test the import given a name part of the problem.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • Sounds great but, that implies explicit import. I would like to build something plugins based http://stackoverflow.com/questions/932069/building-a-minimal-plugin-architecture-in-python. – Ali SAID OMAR May 03 '16 at 12:15
  • 1
    If all you need from `argparse` is the name of the plugin to import, the `subparsers` mechanism may be too much. Any string argument would work. You could even collect the allowable names in a `choices` parameter. – hpaulj May 03 '16 at 16:03