I am using following code, I want to show help message if no argument is used. But when I use parser.print_help()
the compiler returns NameError: name 'parser' is not defined
. If I use args.print_help()
the compiler returns AttributeError: 'Namespace' object has no attribute 'print_help'
.
import os,subprocess,argparse
def parse_args():
parser = argparse.ArgumentParser(description='Generate a power comparision report.')
# Define command-line arguments
parser.add_argument('-t', dest='test', help='test1,tes2,...etc')
return parser.parse_args()
def main():
args = parse_args()
if args.test is None :
print("n run will start for all test cases in 3 mins,n following are the default values, use switches to change them")
parser.print_help()
if __name__ == "__main__":
main()
I am expecting a way to print help message if no argument is provided.
1
You need to restructure this a bit so that the arg parsing happens where you want to print help. I usually structure things this way:
#!/usr/bin/env python3
import sys
import os
import argparse
def main(args):
# Do things with args...
if __name__ == "__main__":
# Define command-line arguments
parser = argparse.ArgumentParser(description='Generate a power comparison report.')
parser.add_argument('-t', dest='test', help='test1,tes2,...etc')
if len(sys.argv) == 1:
parser.print_help(sys.stderr)
sys.exit(1)
else:
args = parser.parse_args()
main(args)