0

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.

Eular
  • 1,707
  • 4
  • 26
  • 50
  • I don't think I follow - in 3.x what happens is that the command line parses successfully: you get `Namespace(choice=None)`. But if you "don't want to make the subparser required"... then isn't that a valid and expected result? No idea where your 2.x result is coming from, as I'm not set up to test that. – Karl Knechtel Jun 12 '19 at 19:13
  • [This question](https://stackoverflow.com/questions/22990977/why-does-this-argparse-code-behave-differently-between-python-2-and-3) discusses the same issue, and [this one](https://stackoverflow.com/questions/4042452/display-help-message-with-python-argparse-when-script-is-called-without-any-argu) suggests a solution if you don't want to make the subcommand required. – jirassimok Jun 12 '19 at 19:17
  • Which Python 2 version? Originally subparsers were required. Then a change was made in the 'required argument' test, and subparsers accidentally lost that status. Now `add_subparsers` takes a `required` parameter. https://stackoverflow.com/questions/23349349/argparse-with-required-subparser/23354355#23354355 – hpaulj Jun 12 '19 at 19:57
  • In the older version, you get your help because the subparsers is required. Your custom `error` is called. In the newer code it isn't required, and hence no error call. If you want 'help' without arguments you'll have to find some other way of triggering it - for example checking that `sys.argv[1:]` is empty. – hpaulj Jun 12 '19 at 20:03

0 Answers0