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?
Related
Consider this arg_test.py script:
#!/usr/bin/env python3
import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='subcommand help')
# create the parser for subcommand
parser_a = subparsers.add_parser('do-stuff', help='Help for do-stuff subcommand')
args = parser.parse_args()
With the help for the subcommand I get:
./arg_test.py do-stuff -h
usage: arg_test.py do-stuff [-h]
optional arguments:
-h, --help show this help message and exit
How can I add some usage description when using -h? For example I would like to get:
./arg_test.py do-stuff -h
usage: arg_test.py do-stuff [-h]
This subcommand does awsome stuff << HOW DO I ADD THIS?
optional arguments:
-h, --help show this help message and exit
using argparse i have made a command line tool, which takes below arguments,
usage: ipush [-h] [-v] [-c] [-to [TO]] [-V] [-p PATCHES] [-d DIFF]
from the below code..
parser = argparse.ArgumentParser(prog='ipush',
description='Utility to push the last commit and email the color diff')
parser.add_argument('-v', '--verbose', action='store_true',
help='if enabled will spit every command and its resulting data.')
parser.add_argument('-c', '--compose', action='store_true',
help='compose message in default git editor to be sent prefixed with diff')
parser.add_argument('-to', type=validate_address, default=os.getenv('myemail'),
help='enter a valid email you want to send to.', nargs='?')
parser.add_argument('-V', '--version', action='version',
version='%(prog)s 1.0')
parser.add_argument('-p', '--patches', type=int, default=0,
help='total number of pathces of last commits to email')
parser.add_argument('-d', '--diff', required=False, default='HEAD^ HEAD',
help='if present pass arguments to it as you \
will do to git diff in inverted commas')
is it possible to display TO in [-to [TO]] PATCHES in [-p PATCHES] and DIFF in [-d DIFF] with a different text?
Yes, as described in the argparse documentation:
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', metavar='YYY')
>>> parser.add_argument('bar', metavar='XXX')
>>> parser.parse_args('X --foo Y'.split())
Namespace(bar='X', foo='Y')
>>> parser.print_help()
usage: [-h] [--foo YYY] XXX
positional arguments:
XXX
optional arguments:
-h, --help show this help message and exit
--foo YYY
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
using argparse i have made a command line tool, which takes below arguments,
usage: ipush [-h] [-v] [-c] [-to [TO]] [-V] [-p PATCHES] [-d DIFF]
from the below code..
parser = argparse.ArgumentParser(prog='ipush',
description='Utility to push the last commit and email the color diff')
parser.add_argument('-v', '--verbose', action='store_true',
help='if enabled will spit every command and its resulting data.')
parser.add_argument('-c', '--compose', action='store_true',
help='compose message in default git editor to be sent prefixed with diff')
parser.add_argument('-to', type=validate_address, default=os.getenv('myemail'),
help='enter a valid email you want to send to.', nargs='?')
parser.add_argument('-V', '--version', action='version',
version='%(prog)s 1.0')
parser.add_argument('-p', '--patches', type=int, default=0,
help='total number of pathces of last commits to email')
parser.add_argument('-d', '--diff', required=False, default='HEAD^ HEAD',
help='if present pass arguments to it as you \
will do to git diff in inverted commas')
is it possible to display TO in [-to [TO]] PATCHES in [-p PATCHES] and DIFF in [-d DIFF] with a different text?
Yes, as described in the argparse documentation:
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', metavar='YYY')
>>> parser.add_argument('bar', metavar='XXX')
>>> parser.parse_args('X --foo Y'.split())
Namespace(bar='X', foo='Y')
>>> parser.print_help()
usage: [-h] [--foo YYY] XXX
positional arguments:
XXX
optional arguments:
-h, --help show this help message and exit
--foo YYY
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