Skip to content

Instantly share code, notes, and snippets.

@wzpan

wzpan/getopt.py

Last active Aug 29, 2015
Embed
What would you like to do?
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