Posts

Showing posts with the label Argparse

Argparse Optional Positional Arguments?

Answer : Use nargs='?' (or nargs='*' if you need more than one dir) parser.add_argument('dir', nargs='?', default=os.getcwd()) extended example: >>> import os, argparse >>> parser = argparse.ArgumentParser() >>> parser.add_argument('-v', action='store_true') _StoreTrueAction(option_strings=['-v'], dest='v', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None) >>> parser.add_argument('dir', nargs='?', default=os.getcwd()) _StoreAction(option_strings=[], dest='dir', nargs='?', const=None, default='/home/vinay', type=None, choices=None, help=None, metavar=None) >>> parser.parse_args('somedir -v'.split()) Namespace(dir='somedir', v=True) >>> parser.parse_args('-v'.split()) Namespace(dir='/home/vinay', v=True) >>> parser.parse_args(''.split()) Nam...

Check If Argparse Optional Argument Is Set Or Not

Answer : I think that optional arguments (specified with -- ) are initialized to None if they are not supplied. So you can test with is not None . Try the example below: import argparse as ap def main(): parser = ap.ArgumentParser(description="My Script") parser.add_argument("--myArg") args, leftovers = parser.parse_known_args() if args.myArg is not None: print "myArg has been set (value is %s)" % args.myArg As @Honza notes is None is a good test. It's the default default , and the user can't give you a string that duplicates it. You can specify another default='mydefaultvalue , and test for that. But what if the user specifies that string? Does that count as setting or not? You can also specify default=argparse.SUPPRESS . Then if the user does not use the argument, it will not appear in the args namespace. But testing that might be more complicated: args.foo # raises an AttributeError hasattr(args,...

Case Insensitive Argparse Choices

Answer : Transform the argument into lowercase by using type = str.lower for the -p switch. This solution was pointed out by chepner in a comment. The solution I proposed earlier was type = lambda s : s.lower() which is also valid, but it's simpler to just use str.lower . Using lower in the type is nice way of doing this, if you don't mind loosing the case information. If you want to retain the case, you could define a custom choices class. The choices needs two methods, __contains__ (for testing in ), and iteration (to list the choices). class mylist(list): # list subclass that uses lower() when testing for 'in' def __contains__(self, other): return super(mylist,self).__contains__(other.lower()) choices=mylist(['win64','win32']) parser = argparse.ArgumentParser() parser.add_argument("-p", choices=choices) print(parser.parse_args(["-p", "Win32"])) # Namespace(p='Win32') The ...