Last active
August 29, 2015 14:05
-
-
Save wzpan/bfc3fbe36b8f9a1c403b to your computer and use it in GitHub Desktop.
Python2 example to handle options and 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
import sys, os, getopt | |
TARGET_TYPE = ".log" | |
def process_file(path): | |
''' Process a file. ''' | |
print path | |
def process_dir(path): | |
''' Process a directory. ''' | |
file_list = [] | |
files = os.listdir(path) | |
for file in files: | |
file = os.path.join(path, file) | |
root, ext = os.path.splitext(os.path.basename(file)) | |
if os.path.isfile(file) and ext == TARGET_TYPE: | |
process_file(file) | |
def main(): | |
if len(sys.argv) < 2: | |
print "Arguments should be at least 2." | |
print "python get_blockid.py -f [FILE]" | |
print "python get_blockid.py -d [DIRECTORY]" | |
exit(1) | |
try: | |
opts, args = getopt.getopt(sys.argv[1:], "f:d:", ["file=", "directory="]) | |
for arg, value in opts: | |
if arg in ('-f', '--file'): | |
root, ext = os.path.basename(value) | |
if ext == 'TARGET_TYPE': | |
process_file(value) | |
elif arg in ('-d', '--directory'): | |
process_dir(value) | |
else: | |
print "Argument error. %s" % arg | |
exit(1) | |
except getopt.GetoptError as e: | |
print e | |
exit(1) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment