Skip to content

Instantly share code, notes, and snippets.

@wzpan
Last active August 29, 2015 14:05
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 wzpan/bfc3fbe36b8f9a1c403b to your computer and use it in GitHub Desktop.
Save wzpan/bfc3fbe36b8f9a1c403b to your computer and use it in GitHub Desktop.
Python2 example to handle options and arguments.
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