Created
March 13, 2021 06:20
-
-
Save aarshtalati/1ca75b69cb202467aeed295a10059ddc to your computer and use it in GitHub Desktop.
Python Command Line Argument Parser
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 | |
""" | |
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