All about

When using the argparse module to handle command-line arguments in Python, setting the action parameter of the add_argument function to store_true causes the option to be stored as True when provided and False otherwise. This is commonly used for handling boolean flags.

Here is an example using the argparse module to handle a --verbose option as a boolean flag.

import argparse

# Create ArgumentParser object
parser = argparse.ArgumentParser(description='Example with store_true action')

# Add the --verbose option
parser.add_argument('--verbose', action='store_true', help='Enable verbose mode')

# Parse command-line arguments
args = parser.parse_args()

# Print the parsed results
print(args)

# Execute only if the --verbose option is provided
if args.verbose:
    print('Verbose mode enabled!')
else:
    print('Verbose mode disabled.')

 

When running this script, if you provide the --verbose option, it will be stored as True; otherwise, it will be stored as False. For example,

python script.py --verbose

 

Output:

Namespace(verbose=True)
Verbose mode enabled!

 

python script.py

 

Output:

Namespace(verbose=False)
Verbose mode disabled.

 

This approach is useful for handling simple boolean flags in command-line scripts.

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading