Removing dest variable from help text - python

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.

Related

Python: help menu doesn't show all options when using parse_known_args()

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)

Argparse to show usage help for subcommand

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

Better help for argparse subcommands

Given the following code snippet:
import argparse
import sys
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help="subcommand help")
command1 = subparsers.add_parser("foo", description="Run foo subcommand")
command2 = subparsers.add_parser("bar", description="Run bar subcommand")
opts = parser.parse_args(sys.argv[1:])
When I print help for this I get this:
usage: test.py [-h] {foo,bar} ...
positional arguments:
{foo,bar} subcommand help
optional arguments:
-h, --help show this help message and exit
Is there a way to make it print something like this instead:
usage: test.py [-h] {foo,bar} ...
subcommands:
foo Run foo subcommand
bar Run bar subcommand
optional arguments:
-h, --help show this help message and exit
without supplying a custom formatter? If I change the formatter then it also changes everything else about how the help is printed, but in my case I just want to change the way that subcommand help is printed from the parent (sub)command.
You need to set the help parameter, not the description parameter, to get the output you desire:
import argparse
import sys
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help="subcommand help")
command1 = subparsers.add_parser("foo", help="Run foo subcommand")
command2 = subparsers.add_parser("bar", help="Run bar subcommand")
opts = parser.parse_args(sys.argv[1:])
Output:
usage: test.py [-h] {foo,bar} ...
positional arguments:
{foo,bar} subcommand help
foo Run foo subcommand
bar Run bar subcommand
optional arguments:
-h, --help show this help message and exit
The argparse docs have this to say about the help value:
The help value is a string containing a brief description of the argument. When a user requests help (usually by using -h or --help at the command line), these help descriptions will be displayed with each argument.
And this to say to about the description value:
This argument gives a brief description of what the program does and how it works. In help messages, the description is displayed between the command-line usage string and the help messages for the various arguments.

Python argparse --help description in sentence case

Extremely nitpicky question, but it annoys me that the default argparse help message is a sentence fragment. For example, for a script that contains
#!/usr/bin/env python
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()
The -h and --help flag message shows:
$ tmp.py --help
usage: tmp.py [-h]
optional arguments:
-h, --help show this help message and exit
However I prefer complete sentences in documentation and "sentence case" for headers:
$ tmp.py --help
Usage: tmp.py [-h]
Optional arguments:
-h, --help Show this help message and exit.
How can I keep the behavior of script -h and script --help but change the message?
Welp found the answer 5 seconds later.
#!/usr/bin/env python
import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.parse_args()
parser.add_argument(
'-h', '--help', action='help', help='Show this help message and exit.')
Defining your own action='help' argument is probably the best answer. But it is possible to edit the default help.
All the defined Actions are collected in the parser._actions list. Yes, it is marked hidden, but people do access it as needed. Normally the help action is the first one created (as default), so it is element [0] of that list.
In [15]: parser._actions[0].help
Out[15]: 'show this help message and exit'
In [16]: parser._actions[0].help = "Show this help message and exit."
testing:
In [17]: parser.print_help()
usage: ipython3 [-h] {mySubcommand,m} ...
positional arguments:
{mySubcommand,m} sub-command help
mySubcommand (m)
Subcommand help
optional arguments:
-h, --help Show this help message and exit.
def main():
parser = argparse.ArgumentParser()
# specific file
parser.add_argument('-f', '--file', type=str, default='file',
help=Fore.BLUE + '--file access_log -extract-ip' + Style.RESET_ALL)
# http get file
parser.add_argument('-hgf', '--http-get-file', type=str, default='http-get-file',
help=Fore.BLUE + '--http-get-file URL' + Style.RESET_ALL)

argparser.print_help() not printing the full message

I have a program where I tried to put help in my code using argparse:
import argparse,sys
parser = argparse.ArgumentParser(description='prog desc')
parser.add_argument('path', help='name of directory')
args = parser.parse_args()
parser.print_help()
this prints:
>python testArgs.py
usage: testArgs.py [-h] path
testArgs.py: error: too few arguments
but I'm expecting same as if I entered -h:
>python testArgs.py -h
usage: testArgs.py [-h] path
prog desc
positional arguments:
path name of directory
optional arguments:
-h, --help show this help message and exit
But if I switch the position of the print_help() before parse_args(), then it works right:
import argparse,sys
parser = argparse.ArgumentParser(description='prog desc')
parser.add_argument('path', help='name of directory')
parser.print_help()
args = parser.parse_args()
output:
>python testArgs.py
usage: testArgs.py [-h] path
prog desc
positional arguments:
path name of directory
optional arguments:
-h, --help show this help message and exit
usage: testArgs.py [-h] path
testArgs.py: error: too few arguments
What am I doing wrong?
In your first example your program doesn't reach the parser.print_help() method, it fails on parser.parse_args(), prints the default error message (which is testArgs.py: error: too few arguments) and exits the program.
In your second example, when you switch between the functions, it still behaves the same but you see the help details because you called the print_help() function before the program fails (you can see it fails because it still prints the error message at the end).
If you want to print the help message when an argparse error occurred, read this post:
Display help message with python argparse when script is called without any arguments

Categories

Resources