I'm writing a program that use argparse, for parsing some arguments that I need.
for now I have this:
parser.add_argument('--rename', type=str, nargs=2, help='some help')
when I run this script I see this:
optional arguments:
-h, --help show this help message and exit
--rename RENAME RENAME
some help
How can I change my code in that way that the help "page" will show me:
--rename OLDFILE NEWFILE
Can I then use OLDFILE and NEWFILE value in this way?
args.rename.oldfile
args.rename.newfile
If you set metavar=('OLDFILE', 'NEWFILE'):
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--rename', type=str, nargs=2, help='some help',
metavar=('OLDFILE', 'NEWFILE'))
args = parser.parse_args()
print(args)
Then test.py -h yields
usage: test.py [-h] [--rename OLDFILE NEWFILE]
optional arguments:
-h, --help show this help message and exit
--rename OLDFILE NEWFILE
some help
You can then access the arguments with
oldfile, newfile = args.rename
If you really want to access the oldfile with args.rename.oldfile
you could set up a custom action:
import argparse
class RenameAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest,
argparse.Namespace(
**dict(zip(('oldfile', 'newfile'),
values))))
parser = argparse.ArgumentParser()
parser.add_argument('--rename', type=str, nargs=2, help='some help',
metavar=('OLDFILE', 'NEWFILE'),
action=RenameAction)
args = parser.parse_args()
print(args.rename.oldfile)
but it extra code does not really seem worth it to me.
Read the argparse documentation (http://docs.python.org/2.7/library/argparse.html#metavar):
Different values of nargs may cause the metavar to be used multiple times. Providing a tuple to metavar specifies a different display for each of the arguments:
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x', nargs=2)
>>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
>>> parser.print_help()
usage: PROG [-h] [-x X X] [--foo bar baz]
optional arguments:
-h, --help show this help message and exit
-x X X
--foo bar baz
Related
I went through a "little" issue using python argument parser, I've created a parser like shown below:
parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument('-l', '--log-level', help="log level")
parser.add_argument('-o', '--out-dir', help="output directory")
args, remaining = parser.parse_known_args()
outpu_dir = args.out_dir
parser.add_argument('-f', '--log-file', help = "log file directory")
args = parser.parse_args()
and the problem is that when calling the program with --help option, arguments added after parse_known_args() are not listed in the menu, I checked other topics related to this, but my case is a bit different! could any one give a help here please ?
Any code which is below the call to parse_known_args will not execute at all.
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('-a')
parser.parse_known_args()
1/0
When running with --help this generates
usage: main.py [-h] [-a A]
optional arguments:
-h, --help show this help message and exit
-a A
Process finished with exit code 0
and not a ZeroDivisionError exception.
You can work around it by adding the help option after all the other args have been added & you've parsed the known args.
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter, SUPPRESS
# don't add help right now
parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter, add_help=False)
parser.add_argument('-l', '--log-level', help="log level")
parser.add_argument('-o', '--out-dir', help="output directory")
args, remaining = parser.parse_known_args()
outpu_dir = args.out_dir
parser.add_argument('-f', '--log-file', help="log file directory")
# add help later, when all other args have been added
parser.add_argument('-h', '--help', action='help', default=SUPPRESS,
help='Show this help message and exit.')
args = parser.parse_args()
Which results in:
(venv) ➜ python main.py --help
usage: main.py [-l LOG_LEVEL] [-o OUT_DIR] [-f LOG_FILE] [-h]
optional arguments:
-l LOG_LEVEL, --log-level LOG_LEVEL
log level (default: None)
-o OUT_DIR, --out-dir OUT_DIR
output directory (default: None)
-f LOG_FILE, --log-file LOG_FILE
log file directory (default: None)
-h, --help Show this help message and exit.
But it's much better if you can restructure your code to add all the argusments first before doing any parsing (i.e. avoid the call to parse_known_aergs before any other add_argument calls)
I'm trying to write a script that would take some flags and files as arguments and then execute other scripts, depend on the flag that the user chooses. For example, the command line should look like that:
main_script.py -flag1 -file_for_flag_1 another_file_for_flag_1
and
main_script.py -flag2 -file_for_flag_2
I tried to use the argparse library, but I don't know how to take the input files as arguments for the next steps and manipulate them as I want. I started with:
parser = argparse.ArgumentParser(description="Processing inputs")
parser.add_argument(
"-flat_map",
type=str,
nargs="+",
help="generates a flat addressmap from the given files",
)
parser.add_argument(
"-json_convert",
type=str,
nargs="+",
help="generates a flat addressmap from the given files",
)
args = parser.parse_args(args=["-flat_map"])
print(args)
I printed args in the end to see what I get from it but I got nothing I can work with.
Would like to have some guidance. Thanks.
You can convert the args to a dict (where the key is the arg option and the value is the arg value) if it's more convenient for you:
args_dict = {key: value for key, value in vars(parser.parse_args()).items() if value}
Using argparse you can use sub-commands to select sub-modules:
import argparse
def run_command(parser, args):
if args.command == 'command1':
# add code for command1 here
print(args)
elif args.command == 'command2':
# add code for command2 here
print(args)
parser = argparse.ArgumentParser(
prog='PROG',
epilog="See '<command> --help' to read about a specific sub-command."
)
subparsers = parser.add_subparsers(dest='command', help='Sub-commands')
A_parser = subparsers.add_parser('command1', help='Command 1')
A_parser.add_argument("--foo")
A_parser.add_argument('--bar')
A_parser.set_defaults(func=run_command)
B_parser = subparsers.add_parser('command2', help='Command 2')
B_parser.add_argument('--bar')
B_parser.add_argument('--baz')
B_parser.set_defaults(func=run_command)
args = parser.parse_args()
if args.command is not None:
args.func(parser, args)
else:
parser.print_help()
This generates a help page like so:
~ python args.py -h
usage: PROG [-h] {command1,command2} ...
positional arguments:
{command1,command2} Sub-commands
command1 Command 1
command2 Command 2
optional arguments:
-h, --help show this help message and exit
See '<command> --help' to read about a specific sub-command.
and help text for each sub-command:
~ python args.py B -h
arg.py command2 -h
usage: PROG command2 [-h] [--bar BAR] [--baz BAZ]
optional arguments:
-h, --help show this help message and exit
--bar BAR
--baz BAZ
While using argparse, the help dialog of my program displays dest variable. How do I remove this?
I tried the add_help=False object but that just removed the help dialog for that option entirely.
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--interface", dest="interface", help="foo")
parser.add_argument("-m", "--mac", dest="mac", help="bar")
I get the following result with INTERFACE and MAC next to my optional arguments:
usage: test.py [-h] [-i INTERFACE] [-m MAC]
optional arguments:
-h, --help show this help message and exit
-i INTERFACE, --interface INTERFACE
foo
-m MAC, --mac MAC bar
How can I remove DEST values from my output?
As #hpaulj suggested, you can set the metavar parameter of each argument to an empty string
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--interface", dest="interface", help="foo", metavar='')
parser.add_argument("-m", "--mac", dest="mac", help="bar", metavar='')
parser.parse_args()
which will output the following result:
usage: test.py [-h] [-i] [-m]
optional arguments:
-h, --help show this help message and exit
-i , --interface foo
-m , --mac bar
Let me know if that's the output you expected.
I have the following python:
import argparse
parser = argparse.ArgumentParser()
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('-h', '--host_name', required=True, help="Host IP address")
args = parser.parse_args()
This produces the following error:
argparse.ArgumentError: argument -h/--help: conflicting option string(s): -h
Every single letter works fine except -h. It seems like it is reserved for --help. How can I make it so that it isn't -h isn't automatically reserved?
ArgumentParser takes an optional parameter add_help which you can set False.
In the documentation for add_help:
Occasionally, it may be useful to disable the addition of this help option. This can be achieved by passing False as the add_help= argument to ArgumentParser:
>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
>>> parser.add_argument('--foo', help='foo help')
>>> parser.print_help()
usage: PROG [--foo FOO]
optional arguments:
--foo FOO foo help
If I have code such as this:
import argparse
# create the top-level parser
parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('--foo', action='store_true', help='foo help')
subparsers = parser.add_subparsers(help='sub-command help')
# create the parser for the "a" command
parser_a = subparsers.add_parser('a', help='a help')
parser_a.add_argument('bar', type=int, help='bar help')
# create the parser for the "b" command
parser_b = subparsers.add_parser('b', help='b help')
parser_b.add_argument('--baz', choices='XYZ', help='baz help')
parser.parse_args()
Asking for the help in a subparser results in:
$ ./test.py a -h
usage: PROG a [-h] bar
positional arguments:
bar bar help
optional arguments:
-h, --help show this help message and exit
How do I make it show the --foo option and the help for it, when asking for the help in a subparser?