I am trying to figure out if it is possible to have different description printed depending on the input of the user using argparse in Python.
I have the following messages that I want my program to print out.
general_help = '''httpc is a curl-like application but supports HTTP protocol only.
Usage:
httpc command [arguments]
The commands are:
get executes a HTTP GET request and prints the response.
post executes a HTTP POST request and prints the response.
help prints this screen.
Use "httpc help [command]" for more information about a command.\n
'''
get_help = '''usage: httpc get [-v] [-h key:value] URL
Get executes a HTTP GET request for a given URL.
-v Prints the detail of the response such as protocol, status, and headers.
-h key:value Associates headers to HTTP Request with the format 'key:value'.\n
'''
post_help = '''usage: httpc post [-v] [-h key:value] [-d inline-data] [-f file] URL
Post executes a HTTP POST request for a given URL with inline data or from file.
-v Prints the detail of the response such as protocol, status, and headers.
-h key:value Associates headers to HTTP Request with the format 'key:value'.
-d string Associates an inline data to the body HTTP POST request.
-f file Associates the content of a file to the body HTTP POST request.
Either [-d] or [-f] can be used but not both.\n
'''
I would like for my program to print the general_help when the user enters python httpc.py -h
, the get_help when the user enters python httpc.py -h get
and the post_message when the user enters python httpc.py -h post
For now, what I have is the following which prints out all the messages
parser = argparse.ArgumentParser(description=(general_help + get_help + post_help),
formatter_class=RawTextHelpFormatter)
parser.add_argument("--port", help="server port", type=int, default=80)
parser.add_argument("httpc", help="get or post, string. request type.", type=str)
parser.add_argument("URL", help="given URL to send requests to", type=str)
parser.add_argument("-v", help="sets verbosity to true", action="store_true")
parser.add_argument("-header", help="additional header line for the request, host is autogenerated", type=str, default=None)
parser.add_argument("-d", help=" inline data to be used as body of request", type=str, default=None)
parser.add_argument("-f", help="fielpath for body data", type=str, default=None)
args = parser.parse_args()
you use subparsers
p = argparse.ArgumentParser()
subcommands = p.add_subparsers(dest="selected_action")
p1 = subcommands.add_parser("httpc",help=...)
p1.add_argument("url",help=...)
p1.add_argument("-p",help="port num",default=8080)
p2 = subcommands.add_parser("get",help=...)
...
p.parse_args(["--help"])
p.parse_args(["httpc","--help"])