Building CLI Arguments
Types of Arguments
graph TD
A[Argument Types] --> B[Positional Arguments]
A --> C[Optional Arguments]
A --> D[Flag Arguments]
Positional Arguments
Positional arguments are required and their order matters:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('filename', help='Input file name')
parser.add_argument('output', help='Output file name')
args = parser.parse_args()
Optional Arguments
Optional arguments use flags and can have default values:
parser.add_argument('--port',
type=int,
default=8000,
help='Server port number')
parser.add_argument('-v', '--verbose',
action='store_true',
help='Enable verbose mode')
Argument Configuration Options
Option |
Description |
Example |
type |
Specify argument type |
type=int |
default |
Set default value |
default=8000 |
help |
Provide description |
help='Server port' |
required |
Make argument mandatory |
required=True |
Advanced Argument Actions
parser.add_argument('--log',
choices=['DEBUG', 'INFO', 'WARNING'],
help='Set logging level')
parser.add_argument('--numbers',
nargs='+',
type=int,
help='Accept multiple numbers')
Mutually Exclusive Arguments
group = parser.add_mutually_exclusive_group()
group.add_argument('--quiet', action='store_true')
group.add_argument('--verbose', action='store_true')
Complete Example
import argparse
def main():
parser = argparse.ArgumentParser(description='Advanced CLI Example')
## Positional argument
parser.add_argument('input', help='Input file path')
## Optional arguments
parser.add_argument('--output',
default='output.txt',
help='Output file path')
## Flag argument
parser.add_argument('-v', '--verbose',
action='store_true',
help='Enable verbose mode')
## Parse arguments
args = parser.parse_args()
## Use arguments
if args.verbose:
print(f"Processing {args.input} to {args.output}")
if __name__ == '__main__':
main()
Argument Validation
def positive_int(value):
ivalue = int(value)
if ivalue <= 0:
raise argparse.ArgumentTypeError(f"{value} is not a positive integer")
return ivalue
parser.add_argument('--count',
type=positive_int,
help='Positive integer count')
Best Practices
- Always provide helpful help messages
- Use type conversion for input validation
- Set reasonable default values
- Use mutually exclusive groups when appropriate
LabEx recommends practicing these techniques to create robust command-line interfaces that are both user-friendly and powerful.