上QQ阅读APP看书,第一时间看更新
Getting ready
The basic use of argparse in a script can be shown in three steps:
- Define the arguments that your script is going to accept, generating a new parser.
- Call the defined parser, returning an object with all the resulting arguments.
- Use the arguments to call the entry point of your script, which will apply the defined behavior.
Try to use the following general structure for your scripts:
IMPORTS
def main(main parameters):
DO THINGS
if __name__ == '__main__':
DEFINE ARGUMENT PARSER
PARSE ARGS
VALIDATE OR MANIPULATE ARGS, IF NEEDED
main(arguments)
The main function makes it easy to know what the entry point for the code is. The section under the if statement is only executed if the file is called directly, but not if it's imported. We'll follow this for all the steps.