[파이썬] argparse 대화형 모드와 argparse 통합

Argparse is a powerful module in Python that allows you to easily parse command-line arguments and options. It provides a convenient way to create interactive command-line interfaces for your Python applications. In this blog post, we will explore two different aspects of argparse - the interactive mode and integrating argparse with other modules.

Argparse Interactive Mode

By default, argparse works in a non-interactive mode where the user provides command-line arguments when running the script. However, sometimes it can be useful to have an interactive mode where the user is prompted to enter the arguments during runtime.

The argparse module provides an argparse.ArgumentParser class that can be used to create an interactive mode. Let’s see an example:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--name", help="Enter your name")
parser.add_argument("--age", type=int, help="Enter your age")

args = parser.parse_args()
print(f"Hello {args.name}, you are {args.age} years old!")

In this example, the user is prompted to enter their name and age. The --name and --age are the arguments that the user needs to provide. The help parameter is used to display a message prompting the user to enter the argument.

To run this interactive script, you can use the following command:

python script.py --name John --age 25

Argparse Integration with other modules

Argparse can be easily integrated with other modules to further enhance the functionality and usability of your Python applications. Let’s take a look at an example of integrating argparse with the requests module:

import argparse
import requests

parser = argparse.ArgumentParser()
parser.add_argument("--url", help="Enter the URL")

args = parser.parse_args()

response = requests.get(args.url)

if response.status_code == 200:
    print(f"Success! The URL {args.url} is accessible.")
else:
    print(f"Error! The URL {args.url} is not accessible.")

In this example, we are using argparse to accept a URL as an argument. We then use the requests module to send an HTTP GET request to the provided URL. Based on the response status code, we display a success or error message.

To run this script, you can use the following command:

python script.py --url https://www.example.com

This is just a simple example, but it shows the potential of integrating argparse with other modules to create powerful and interactive command-line applications.

In conclusion, argparse provides a convenient way to create interactive command-line interfaces and can be easily integrated with other modules to enhance the functionality of your Python applications. Whether you need an interactive mode or want to combine argparse with other modules, argparse is a versatile tool that can help you build robust command-line applications.