Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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