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?
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With