mirror of
https://github.com/Brandon-Rozek/website.git
synced 2024-11-25 09:36:31 -05:00
58 lines
No EOL
1.8 KiB
Markdown
58 lines
No EOL
1.8 KiB
Markdown
---
|
|
aliases:
|
|
- /blog/python-argpase/
|
|
date: 2022-05-16 17:07:06-04:00
|
|
draft: false
|
|
math: false
|
|
medium_enabled: true
|
|
medium_post_id: 7d4c148bd2d0
|
|
tags:
|
|
- Python
|
|
title: Python Argument Parser
|
|
---
|
|
|
|
*For a much better description of argument parsing in Python, please visit https://docs.python.org/3/library/argparse.html.*
|
|
|
|
I'm creating this post because even though it's not too complicated, I keep forgetting how to do argument parsing in Python. I also tricked myself into thinking each time that I already wrote a blog post on this. Let's correct this once and for all and include a quick example!
|
|
|
|
```python
|
|
import argparse
|
|
parser = argparse.ArgumentParser(description="Description to show in help")
|
|
parser.add_argument("pos_arg1", type=str, help="Required positional argument")
|
|
parser.add_argument("--flag1", type=str, help="Optional flag argument")
|
|
parser.add_argument("--flag2", type=int, required=True, help="Required flag argument")
|
|
parser.add_argument("--flag3", type=int, default=0, help="Optional flag argument \
|
|
with default value of 0")
|
|
args = vars(parser.parse_args())
|
|
```
|
|
|
|
Now if you call the program with no arguments you'll get the following message:
|
|
|
|
```
|
|
usage: testarg.py [-h] [--flag1 FLAG1] --flag2 FLAG2 pos_arg1
|
|
testarg.py: error: the following arguments are required: pos_arg1, --flag2
|
|
```
|
|
|
|
This comes with a built in `-h` as well!
|
|
|
|
```
|
|
usage: testarg.py [-h] [--flag1 FLAG1] --flag2 FLAG2 pos_arg1
|
|
|
|
Description to show in help
|
|
|
|
positional arguments:
|
|
pos_arg1 Required positional argument
|
|
|
|
optional arguments:
|
|
-h, --help show this help message and exit
|
|
--flag1 FLAG1 Optional flag argument
|
|
--flag2 FLAG2 Required flag argument
|
|
```
|
|
|
|
Within the code you can parse the argument names by accessing the `args` dictionary.
|
|
|
|
```python
|
|
pos_arg1 = args['pos_arg1']
|
|
flag1 = args['flag1']
|
|
flag2 = args['flag2']
|
|
``` |