1

I have a program where I tried to put help in my code using argparse:

import argparse,sys

parser = argparse.ArgumentParser(description='prog desc')
parser.add_argument('path', help='name of directory')
args = parser.parse_args() 
parser.print_help()

this prints:

>python testArgs.py
usage: testArgs.py [-h] path
testArgs.py: error: too few arguments

but I'm expecting same as if I entered -h:

>python testArgs.py -h
usage: testArgs.py [-h] path

prog desc

positional arguments:
  path        name of directory

optional arguments:
  -h, --help  show this help message and exit

But if I switch the position of the print_help() before parse_args(), then it works right:

import argparse,sys

parser = argparse.ArgumentParser(description='prog desc')
parser.add_argument('path', help='name of directory')
parser.print_help()
args = parser.parse_args() 

output:

>python testArgs.py
usage: testArgs.py [-h] path

prog desc

positional arguments:
  path        name of directory

optional arguments:
  -h, --help  show this help message and exit
usage: testArgs.py [-h] path
testArgs.py: error: too few arguments

What am I doing wrong?

Ching Liu
  • 1,527
  • 2
  • 11
  • 15
  • when `parse_args()` catches an error like this, it displays `usage`, and then exits. The script doesn't continue on to the `print_help`. The other way to trigger help is to use the '-h' commandline. – hpaulj Sep 27 '19 at 21:47

1 Answers1

1

In your first example your program doesn't reach the parser.print_help() method, it fails on parser.parse_args(), prints the default error message (which is testArgs.py: error: too few arguments) and exits the program.

In your second example, when you switch between the functions, it still behaves the same but you see the help details because you called the print_help() function before the program fails (you can see it fails because it still prints the error message at the end).

If you want to print the help message when an argparse error occurred, read this post: Display help message with python argparse when script is called without any arguments