argparse action or type for comma-separated list

The simplest solution is to consider your argument as a string and split. #!/usr/bin/env python3 import argparse parser = argparse.ArgumentParser() parser.add_argument(“–myarg”, type=str) args = parser.parse_args() if args.myarg is not None: args.myarg = [s.strip() for s in args.myarg.split(“,”)] print(args) Result: $ ./toto.py –myarg=abcd,e,fg Namespace(myarg=[‘abcd’, ‘e’, ‘fg’]) $ ./toto.py –myarg=”abcd, e, fg” Namespace(myarg=[‘abcd’, ‘e’, ‘fg’])

Python: argparse optional arguments without dashes

There is no way to get argparse to do this for you. However, you can make argparse accept any number of positional arguments: parser.add_argument(‘FILES’,nargs=”*”) options=parser.parse_args() file1,optional_files=options.FILES[0],options.FILES[1:] Of course, you may want to add some checks to make sure that at least 1 file was given, etc. EDIT I’m still not 100% sure what you want … Read more

Python argparse fails to parse hex formatting to int type

argparse is looking to create a callable type conversion from the ‘type’ value: def _get_value(self, action, arg_string): type_func = self._registry_get(‘type’, action.type, action.type) if not _callable(type_func): msg = _(‘%r is not callable’) raise ArgumentError(action, msg % type_func) # convert the value to the appropriate type try: result = type_func(arg_string) # ArgumentTypeErrors indicate errors except ArgumentTypeError: name … Read more

how to set logging level from command line

The basicConfig function can take a string argument for level, and it will check its validity for you, so the code can be much simpler than BarryPye’s answer. import argparse import logging parser = argparse.ArgumentParser() parser.add_argument( ‘-log’, ‘–loglevel’, default=”warning”, help=’Provide logging level. Example –loglevel debug, default=warning’ ) args = parser.parse_args() logging.basicConfig( level=args.loglevel.upper() ) logging.info( ‘Logging … Read more

Python argparse integer condition (>=12) [duplicate]

One way is to use a custom type. def bandwidth_type(x): x = int(x) if x < 12: raise argparse.ArgumentTypeError(“Minimum bandwidth is 12”) return x parser.add_argument(“-b”, “–bandwidth”, type=bandwidth_type, help=”target bandwidth >= 12″) Note: I think ArgumentTypeError is a more correct exception to raise than ArgumentError. However, ArgumentTypeError is not documented as a public class by argparse, … Read more

Python argparse – Mutually exclusive group with default if no argument is given

You could have each of your actions update the same variable, supplying stdout as the default value for that variable. Consider this program: import argparse parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument( ‘-s’, ‘–stdout’, action=’store_const’, dest=”type”, const=”s”, default=”s”) group.add_argument( ‘-c’, ‘–csv’, action=’store_const’, dest=”type”, const=”c”) group.add_argument( ‘-t’, ‘–txt’, action=’store_const’, dest=”type”, const=”t”) args = parser.parse_args() print args … Read more

Python argparse regex

The type keyword argument can take any callable that accepts a single string argument and returns the converted value. If the callable raises argparse.ArgumentTypeError, TypeError, or ValueError, the exception is caught and a nicely formatted error message is displayed. import argparse import re from uuid import uuid4 def my_regex_type(arg_value, pat=re.compile(r”^[a-f0-9A-F]{32}$”)): if not pat.match(arg_value): raise argparse.ArgumentTypeError(“invalid … Read more

Disable/Remove argument in argparse

Is it possible to remove or disable an argument in argparse, such that it does not show in the help? Set help to argparse.SUPPRESS when you add the argument, like this: parser.add_argument(‘–arg1’, help=argparse.SUPPRESS) This will prevent the argument from showing up in the default help output.

Multiple lines in python argparse help display

The default help formatter re-wraps lines to fit your terminal (it looks at the COLUMNS environment variable to determine the output width, defaulting to 80 characters total). From the formatter_class section: By default, ArgumentParser objects line-wrap the description and epilog texts in command-line help messages. Use the RawTextHelpFormatter class instead to indicate that you already … Read more