How can options/arguments determine which function is chosen during program execution? For the example I have two options depending on the option I would like them to use their respective functions. What am I missing?
import os, sys, glob
from optparse import OptionParser
def fname(arguments):
files = []
for arg in arguments:
if '*' in arg or '?' in arg:
# contains a wildcard character
files.extend(glob.glob(arg))
elif os.path.isdir(arg):
# is a dictionary
files.extend(glob.glob(os.path.join(arg, '*')))
elif os.path.exists(arg):
# is a file
files.append(arg)
else:
# invalid?
print '%s invalid' % arg
return files
# check if file exists locally, if not: download it
def downnload(filename, keyString):
if not os.path.exists(filename+keyString):
l.get_contents_to_filename(filename+keyString)
# List bucket contents
def blist(bucket):
for b in rs:
print b.name
def main():
usage = "usage: %prog [options] -f filename"
parser = OptionParser(usage)
parser.add_option('-d', '--download',
action='store', dest='download',
default=None, help='download files from cloud')
parser.add_option('-l', '--list',
action='store', dest='bucket',
default=None, help='list buckets or contents of specified bucket')
if len(sys.argv) == 1:
parser.print_help()
sys.exit()
(options, args) = parser.parse_args()
# from boto import
bucket_list = bucket.list()
for l in bucket_list:
keyString = str(l.key)
downnload(options.filename, keyString)
blist(options.bucket)
if __name__ == '__main__':
main()
You are missing a lot.
filenamegiven a value?keyStringgiven a value?bucketgiven a value?listsince that it is a primitive typeYou probably want to look at the
optparsetutorial. I’m assuming that you expectingbucketto receive the value from the--listcommand line argument. The value gets stored intooptions.bucketinstead. That is just a start.I think that you want to change the end of
mainto check the options and call the appropriate function. Something like:I think that this is what you are looking for. It decides which function to call based on the command line arguments passed in. For example, if the user passes
--download filenamethen thedownnloadfunction is called with the supplied filename as the argument.