comparison cmd2.py @ 187:183dd2fffec5 0.4.5

newline terminators ok
author catherine@Elli.myhome.westell.com
date Wed, 28 Jan 2009 12:37:02 -0500
parents bee79220382c
children 06119abd352e
comparison
equal deleted inserted replaced
186:bee79220382c 187:183dd2fffec5
41 If you override this in a subclass, it should not return -- it 41 If you override this in a subclass, it should not return -- it
42 should either exit or raise an exception. 42 should either exit or raise an exception.
43 """ 43 """
44 raise 44 raise
45 45
46 def remainingArgs(oldArgs, newArgList):
47 '''
48 >>> remainingArgs('-f bar bar cow', ['bar', 'cow'])
49 'bar cow'
50 '''
51 pattern = '\s+'.join(newArgList) + '\s*$'
52 matchObj = re.search(pattern, oldArgs)
53 return oldArgs[matchObj.start():]
54
46 def options(option_list): 55 def options(option_list):
47 def option_setup(func): 56 def option_setup(func):
48 optionParser = OptionParser() 57 optionParser = OptionParser()
49 for opt in option_list: 58 for opt in option_list:
50 optionParser.add_option(opt) 59 optionParser.add_option(opt)
51 optionParser.set_usage("%s [options] arg" % func.__name__.strip('do_')) 60 optionParser.set_usage("%s [options] arg" % func.__name__.strip('do_'))
52 def newFunc(instance, arg): 61 def newFunc(instance, arg):
53 try: 62 try:
54 opts, newArgs = optionParser.parse_args(arg.split()) 63 opts, newArgList = optionParser.parse_args(arg.split())
55 newArgs = (newArgs and arg[arg.find(newArgs[0]):]) or '' 64 newArgs = remainingArgs(arg, newArgList)
56 except (optparse.OptionValueError, optparse.BadOptionError, 65 except (optparse.OptionValueError, optparse.BadOptionError,
57 optparse.OptionError, optparse.AmbiguousOptionError, 66 optparse.OptionError, optparse.AmbiguousOptionError,
58 optparse.OptionConflictError), e: 67 optparse.OptionConflictError), e:
59 print e 68 print e
60 optionParser.print_help() 69 optionParser.print_help()
61 return 70 return
62 if hasattr(opts, '_exit'): 71 if hasattr(opts, '_exit'):
63 return None 72 return None
64 arg = arg.parser('%s %s%s%s' % (arg.parsed.command, newArgs, arg.parsed.terminator, arg.parsed.suffix)) 73 terminator = arg.parsed.terminator
74 try:
75 if arg.parsed.terminator[0] == '\n':
76 terminator = arg.parsed.terminator[0]
77 except IndexError:
78 pass
79 arg = arg.parser('%s %s%s%s' % (arg.parsed.command, newArgs, terminator, arg.parsed.suffix))
65 result = func(instance, arg, opts) 80 result = func(instance, arg, opts)
66 return result 81 return result
67 newFunc.__doc__ = '%s\n%s' % (func.__doc__, optionParser.format_help()) 82 newFunc.__doc__ = '%s\n%s' % (func.__doc__, optionParser.format_help())
68 return newFunc 83 return newFunc
69 return option_setup 84 return option_setup