[파이썬] argparse 인수의 데이터 타입 지정

argparse is a powerful module in Python for handling command-line arguments. It allows you to define and customize the options and arguments that can be passed to your script. One essential feature of argparse is the ability to specify the data type of the arguments.

By specifying the data type of an argument, argparse can automatically convert the input value into the desired type. This saves you from writing additional code to validate and convert the arguments manually.

Let’s dive into how you can specify the data type of arguments using argparse.

Basic argument declaration

To declare an argument with a specific data type, you can pass the type parameter to the add_argument method. Here’s an example:

import argparse

# Creating the parser
parser = argparse.ArgumentParser()

# Adding an integer argument
parser.add_argument('--age', type=int, help='Enter your age')

# Parsing the arguments
args = parser.parse_args()

In the above example, the age argument is declared as an integer by passing type=int to the add_argument method. This means that when the user provides a value for --age, it will automatically be converted into an integer.

If the user provides an invalid input, such as a non-integer value for --age, argparse will raise an error.

Common data types

argparse supports various data types, including:

Here’s an example that demonstrates the usage of different data types:

import argparse

# Creating the parser
parser = argparse.ArgumentParser()

# Adding arguments with different data types
parser.add_argument('--age', type=int, help='Enter your age')
parser.add_argument('--height', type=float, help='Enter your height')
parser.add_argument('--name', type=str, help='Enter your name')
parser.add_argument('--is_student', type=bool, help='Are you a student?')
parser.add_argument('--numbers', nargs='+', type=int, help='Enter numbers')

# Parsing the arguments
args = parser.parse_args()

In the above example, the age, height, and name arguments have their respective data types specified. The is_student argument is declared as a boolean by passing type=bool. The numbers argument is declared as a list of integers by passing nargs='+' and type=int, which allows the user to enter multiple integers at once.

Conclusion

By specifying the data type of arguments, argparse can handle the conversion and validation of input values automatically. This helps in creating robust and user-friendly command-line interfaces for your Python scripts.

Remember to use the type parameter when adding arguments to your argparse parser and take advantage of the available data types for more accurate argument handling.