Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argparse -- add optional arguments in help string

I have some script on python and argparse, one of optional arguments adds transliteration:

parser = argparse.ArgumentParser()
parser.add_argument('-t', '--text',  
                    action='store_true',
                    help='display a text')
parser.add_argument('-s', '--search', 
                    dest='string', 
                    action='store', 
                    type=str,
                    help='search in a text')
parser.add_argument('--translit', 
                    action='store_true',
                    help='transliterate output; usage: prog [-t | -d STRING] --translit')

results = parser.parse_args()

if len(sys.argv) == 1:
    parser.print_help()
elif results.text and results.translit::
    translit(display_text())
elif results.text and results.translit::
    display_text()
elif results.string and results.translit:
    translit(search(results.string))
elif results.string:
    search(results.string)

Output:

usage: prog [-h] [-t] [-s STRING] [--translit]

optional arguments:
  -h, --help                  show this help message and exit
  -t, --text                  display a text
  -s STRING, --search STRING  search in a text
  --translit                  transliterate output; usage: prog 
                              [-t | -s STRING] --translit

There is no output, when I run prog --translit. I need the string looking so:

usage: prog [-h] [-t] [-s STRING] [[-t | -s STRING] --translit]

When I run prog --translit, the string of output should be:

prog: error: argument --translit: usage: [[-t | -s STRING] --translit]

How can I do this?

like image 891
Covx Avatar asked Oct 01 '22 19:10

Covx


2 Answers

You could make translit a subparser/subcommand which would work as prog translit -h or just prog translit which if there are needed options missing, would display the help text.

Something along the lines of

parser = argparse.ArgumentParser()
parser.add_argument('-s', '--string', required=True)
subparsers = parser.add_subparsers(dest='subcommand_name')
translit_parser = subparsers.add_parser('translit')
translit_parser.add_argument('x', required=True)
parser.parse_args()

python test.py translit would output something like:

usage: test.py translit [-h] -x X
test.py translit: error: argument -x is required
like image 78
Silfheed Avatar answered Oct 05 '22 11:10

Silfheed


You probably should write a separate condition for that since there is none that is exclusively checking for that:

elif results.translit:
    parser.print_help()
like image 20
Spade Avatar answered Oct 05 '22 10:10

Spade