Skip to content

Instantly share code, notes, and snippets.

@jreisinger
Created November 21, 2017 07:57
Show Gist options
  • Save jreisinger/c3fa5785440e2aacd6e7e67f144e8e2c to your computer and use it in GitHub Desktop.
Save jreisinger/c3fa5785440e2aacd6e7e67f144e8e2c to your computer and use it in GitHub Desktop.
Parse command line arguments in Python using sys.argv
#!/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