Differences
This shows you the differences between two versions of the page.
python_wiki:argument_parser [2017/09/02 18:35] billdozor created |
python_wiki:argument_parser [2019/05/25 23:50] |
||
---|---|---|---|
Line 1: | Line 1: | ||
- | ====== Argument Parser ====== | ||
- | |||
- | **General Information** | ||
- | |||
- | Create Python scripts that use short and long arguments. | ||
- | |||
- | **Checklist** | ||
- | * Import argparse | ||
- | |||
- | ---- | ||
- | |||
- | ====== Usage ====== | ||
- | |||
- | Pass the " | ||
- | <code bash> | ||
- | program-name.py -h | ||
- | </ | ||
- | |||
- | ---- | ||
- | |||
- | ====== The Code ====== | ||
- | |||
- | <code python program-name.py> | ||
- | # | ||
- | # Import Modules | ||
- | # | ||
- | # argparse: Command line arguments | ||
- | import argparse | ||
- | |||
- | # | ||
- | # Get Script Arguments | ||
- | # | ||
- | # Build argument parser information | ||
- | parser = argparse.ArgumentParser(description=" | ||
- | parser.add_argument(" | ||
- | parser.add_argument(" | ||
- | parser.add_argument(" | ||
- | args = vars(parser.parse_args()) | ||
- | |||
- | # If testing, we don't actually want to do anything | ||
- | if args[' | ||
- | print(" | ||
- | | ||
- | |||
- | #- Using stored variables from arguments -# | ||
- | |||
- | # Since name is required, program will not run without providing it | ||
- | print(" | ||
- | |||
- | if args[' | ||
- | print(" | ||
- | else | ||
- | print(" | ||
- | </ | ||
- | |||
- | ---- | ||