Sherry Sherry - 1 month ago 7
Python Question

arparse output not aligned

I am using argparse for arguments, I have numbers of argparse statements. I want in the output the capital DELETE should not be print or they should be aligned.
In my case for another argparse the capital words are not aligned in a single column.

parser = argparse.ArgumentParser()
parser.add_argument( '-del' ,action='store' ,dest='delete' , help="Del a POX"
parser.add_argument( '-a' ,action='store' ,dest='add' , help="add a POX"
return parser

python myscript.h -h
-del DELETE Del a POX
-a Add add a POX

Answer

With your parameters I get:

In [417]: parser=argparse.ArgumentParser()
In [418]: a1=parser.add_argument('-del',dest='delete', help='help')
In [419]: a2=parser.add_argument('-a',dest='add', help='help')
In [420]: parser.print_help()
usage: ipython3 [-h] [-del DELETE] [-a ADD]

optional arguments:
  -h, --help   show this help message and exit
  -del DELETE  help
  -a ADD       help

The DELETE and ADD are metavars, standins for the argument that will follow the flag. In the normal help display they follow immediately after the flag, -a ADD. I don't know what is producing the extra space in '-a Add '.

I would have set up your arguments with:

In [421]: parser=argparse.ArgumentParser()
In [422]: a1=parser.add_argument('-d','--delete', help='help')
In [423]: a2=parser.add_argument('-a','--add', help='help')
In [424]: parser.print_help()
usage: ipython3 [-h] [-d DELETE] [-a ADD]

optional arguments:
  -h, --help            show this help message and exit
  -d DELETE, --delete DELETE
                        help
  -a ADD, --add ADD     help

And with the metavar parameter, here an empty string:

In [425]: parser=argparse.ArgumentParser()
In [426]: a1=parser.add_argument('-d','--delete', metavar='', help='help')
In [427]: a2=parser.add_argument('-a','--add', metavar='', help='help')
In [428]: parser.print_help()
usage: ipython3 [-h] [-d] [-a]

optional arguments:
  -h, --help      show this help message and exit
  -d , --delete   help
  -a , --add      help

dest is normally deduced from the first -- flag string; but can, as you do, be set explicitly. metavar is derived from the dest - usually upper cased - in fact I don't know what produces the Add instead of ADD.

It aligns the help portion of the line, but does not align the matavar part.