Created
November 21, 2017 07:57
-
-
Save jreisinger/c3fa5785440e2aacd6e7e67f144e8e2c to your computer and use it in GitHub Desktop.
Parse command line arguments in Python using sys.argv
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import sys | |
import re | |
script = sys.argv.pop(0) | |
while sys.argv: | |
arg = sys.argv.pop(0) | |
# get help with -h/--help | |
if re.search(r'^(-h|--help)$', arg): | |
print('help') | |
# flag | |
elif re.search(r'^(-v|--verbose)$', arg): | |
print('verbose') | |
# option with args | |
elif re.search(r'^(-f|--file)$', arg): | |
param = sys.argv.pop(0) | |
print(arg, '=', param) | |
# positional args - files | |
elif re.search(r'^[^\-]', arg): | |
print('positional arg:', arg) | |
# fallback | |
else: | |
print('wtf:', arg) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment