Created
August 5, 2017 04:06
-
-
Save hmldd/491fe2ab9a65f45da9900354537f956c to your computer and use it in GitHub Desktop.
Python cli (command line) arguments
This file contains 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 python | |
# coding:utf-8 | |
import getopt | |
import sys | |
def main(argv): | |
# Default arguments value | |
start = 1 | |
number = 10 | |
# Get cli arguments | |
try: | |
opts, args = getopt.getopt(argv, "hs:n:", ["start=", "number="]) | |
for opt, arg in opts: | |
if opt == '-h': | |
print_help() | |
elif opt in ("-s", "--start"): | |
start = arg | |
elif opt in ("-n", "--number"): | |
number = arg | |
except getopt.GetoptError: | |
print_help(2) | |
# Use arguments | |
print('Start from: ' + str(start)) | |
print('Number is: ' + str(number)) | |
def print_help(code=0): | |
print('script.py -s <start:1> -n <number:10>') | |
sys.exit(code) | |
if __name__ == '__main__': | |
main(sys.argv[1:]) | |
sys.exit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment