Skip to content

Instantly share code, notes, and snippets.

@aarshtalati
Created March 13, 2021 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aarshtalati/1ca75b69cb202467aeed295a10059ddc to your computer and use it in GitHub Desktop.
Save aarshtalati/1ca75b69cb202467aeed295a10059ddc to your computer and use it in GitHub Desktop.
Python Command Line Argument Parser
#!/usr/bin/env python3
"""
Implement command argument parser
"""
__author__ = "Aarsh Talati"
__version__ = "1.0.0"
__license__ = "GNU General Public License v3.0"
import sys
def main():
"""Print greeting message
"""
print ("hello world")
if __name__ == "__main__":
valid_options = ['--option1', '--option2']
parameters = sys.argv[1:] + [None]
options = {}
key = None
try:
opts = [o for o in sys.argv[1:] if o.startswith("--")]
if not all(o in valid_options for o in opts):
raise ValueError
for p in parameters:
if p == None or p.startswith("--"):
if key is not None:
options[key[2:]] = values
key = p
values = []
else:
values.append(p)
print(options)
main()
except NameError:
print("Invalid syntax. Example: \"-- opt --opt arg arg --opt arg\"")
except ValueError:
print("Invalid option switch. Valid options: ", valid_options)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment