- What is it? When use it?
- Python in-built parser inherited from C language
- “argparse” library
- How to use “argparse”?
- Examples
- Resources
What is it? When use it?
- The rule of thumb is that, if you want to provide a user-friendly approach to configuring your program, then you should consider a command line interface.
- https://docs.python.org/3/library/argparse.html
Python in-built parser inherited from C language
# myls.py
import os
import sys
if len(sys.argv) > 2:
print('You have specified too many arguments')
sys.exit()
if len(sys.argv) < 2:
print('You need to specify the path to be listed')
sys.exit()
input_path = sys.argv[1]
if not os.path.isdir(input_path):
print('The path specified does not exist')
sys.exit()
print('\n'.join(os.listdir(input_path)))“argparse” library
getoptandoptparseare old version of parsers- The Python
argparselibrary: - Allows the use of positional arguments
- Allows the customization of the prefix chars
- Supports variable numbers of parameters for a single option
- Supports subcommands (A main command line parser can use other command line parsers depending on some arguments.)
How to use “argparse”?
- Import the Python
argparselibrary - Create the parser
- Add optional and positional arguments to the parser
- Execute
.parse_args()
Examples
‣
‣