python argparse allowed values

preview_player
Показать описание
Argparse is a powerful module in Python for parsing command-line arguments. When building command-line interfaces (CLIs) using argparse, it's common to restrict the values that users can provide for certain arguments. This tutorial will guide you through using argparse to define allowed values for arguments in your Python scripts.
Start by importing the argparse module in your Python script:
Create an ArgumentParser object to define the command-line arguments your script accepts:
Define the command-line arguments using the add_argument method. To set allowed values, use the choices parameter. Here's an example:
In this example, the --color argument only accepts values 'red', 'green', or 'blue'.
Parse the command-line arguments using the parse_args() method:
Access the values of the parsed arguments through the args object and use them in your script:
Now you can run your script from the command line and test the allowed values:
Try providing an invalid color, and argparse will raise an error.
Here's the complete example script:
Using argparse with allowed values helps ensure that users provide valid inputs to your scripts. This enhances the reliability and usability of your command-line tools. Experiment with different types of allowed values to meet the requirements of your specific applications.
ChatGPT
Рекомендации по теме