So, I'm writing a program in python using argparse
. But my problem is it behaves differently in python 2 and 3. Here's the code
import argparse,sys
class CustomParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('\033[91mError: %s\n\033[0m' % message)
self.print_help()
sys.exit(2)
parser = CustomParser(description='Short sample app')
subparsers = parser.add_subparsers(title='Available sub-commands', dest="choice", help="choose from one of these")
ana = subparsers.add_parser("test",
formatter_class=argparse.RawTextHelpFormatter,
description = 'test',
help ="test")
ana.add_argument("-testf", type=int, help="a test flag", required=True)
args = parser.parse_args()
in python 2 it gives output (just by typing python file.py
no -h
flag)
Error: too few arguments
usage: test.py [-h] {test} ...
Short sample app
optional arguments:
-h, --help show this help message and exit
Available sub-commands:
{test} choose from one of these
test test
But, if I run the same in python 3 (python3 file.py
) it gives no out put. I know if I provide the -h
flag then I can see the description. But I want the help description to appear just by typing python3 file.py
just like the python 2. Also note, I don't want to make the subparser required.