For example, if I input "python prog.py create filename", the result should be create a file named "filename". But I don't know how to put "args" into defination of create. Could someone give me some advice ? This is code:
import argparse
import sys
class ExecuteShell(object):
def create(self, args):
"""create a file"""
print 'xxxxxxxxxxx', args
#return args
def list(self, args):
"""ccccccc"""
print args
#return args
def delete(self, args):
"""ddddddd"""
print 'ddddddd'
#return args
class TestShell(object):
def _find_actions(self, subparsers, actions_module, args):
for attr in (action for action in dir(actions_module) if not action.startswith('__')):
callback = getattr(actions_module, attr)
desc = callback.__doc__ or ''
subparser = subparsers.add_parser(attr, description=desc, add_help=False)
subparser.add_argument('-h', '--help', action='help',
help=argparse.SUPPRESS)
.......
def main(self, args):
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
a = ExecuteShell()
subcommand_parser = self._find_actions(subparsers, a, args)
(options, args) = parser.parse_known_args(args)
if __name__ == "__main__":
a = TestShell()
a.main(sys.argv[1:])
Thanks a lot!
optparseexample? Your use ofparse_known_argssuggests that. So you are creating subparsers that correspond (in name) to the methods (create, etc). But you don't define any arguments. I'd suggest creating a simplerparsermodeled on theset_defaults()example of thesub-commandssection ofargparsedocumentation. Use the parser to parse the input, and then look in the returned Namespace for thecreatecommand and the file name.