7+ Argparse Python 使い方 Ideas
Introduction
Argparse is a Python library used for parsing command-line arguments. It is a standard module in Python, which means it comes pre-installed with the language. Argparse makes it easy to write user-friendly command-line interfaces by providing a simple way to define the arguments a program accepts.What is Command-line Interface?
Command-line interface (CLI) is a way of interacting with a computer program where the user enters commands into a terminal or console. CLI is often used by developers, system administrators, and power users to perform complex tasks quickly and efficiently.Why Use Argparse?
While writing a command-line interface, you need to handle various arguments to provide a smooth experience to the users. Argparse makes it easy to define and handle these arguments. It provides features like type checking, default values, help messages, and more.Installation
Argparse is a standard module in Python, so you don't need to install anything. You can import it like any other module:import argparse
Basic Usage
The first step is to create an instance of theArgumentParser
class: parser = argparse.ArgumentParser()
add_argument()
method. The method takes several arguments like name, type, default value, help message, and more. Here's an example: parser.add_argument('--name', type=str, default='World', help='Name to greet')
--name
to the parser. The argument expects a string value and has a default value of 'World'
. The help message explains what the argument does. After adding all the arguments, you can parse the command-line arguments using the parse_args()
method: args = parser.parse_args()
Advanced Usage
Argparse provides many advanced features like sub-commands, mutually exclusive arguments, argument groups, and more.Sub-commands
You can create sub-commands by creating a new instance of theArgumentParser
class and adding it as a subparser to the main parser: subparsers = parser.add_subparsers(dest='command')
subparsers
variable. You can add sub-commands to the subparser object: hello_parser = subparsers.add_parser('hello', help='Say hello')
hello_parser.add_argument('name', type=str, help='Name to greet')
hello
to the parser. The sub-command expects a string argument called name
. Mutually Exclusive Arguments
You can make arguments mutually exclusive by adding them to anArgumentGroup
object: group = parser.add_mutually_exclusive_group()
group.add_argument('--verbose', action='store_true', help='Verbose output')
group.add_argument('--quiet', action='store_true', help='Quiet output')
0 Response to "7+ Argparse Python 使い方 Ideas"
Posting Komentar