implementation of command line arg passing in python, doesn't work
Question: I'm very new to python. I wish I could implement the command-line arg passing
in python as my first python script. I have written this code:

    
    
    def main(argv):
        try:
            opts, args = getopt.getopt(argv, "hb:b:f", ["help", "bucket=", "folder"])
        except getopt.GetoptError:
            usage()
            sys.exit(2)
        s3 = get_files()
        for opt, arg in opts:
            if opt in ("-h", "--help"):
                usage()
                sys.exit()
            elif opt in ("-b", "--bucket"):
                s3.bucketname = arg
            elif opt in ("-f", "--folder"):
                s3.foldername = arg
                print("Came here" + s3.foldername)
        s3.download_files()
    

In the `-f` argument from command is where I'm facing the problem. For
debugging I used the `print` statement. I pass the arguments like this:

    
    
    ./hello -b something -f /path
    

but sadly it prints out:

    
    
    Came here
    

But the `foldername` attribute is not getting assigned any value. Where I'm
making the mistake?

Thanks in advance.


Answer: Argparse really is a much simpler way of solving problems like this

    
    
    import argparse
    
    if __name__ == "__main__":
        parser = argparse.ArgumentParser()
        parser.add_argument('-b', '--bucket', dest='bucketname', action='store')
        parser.add_argument('-f', '--folder', dest='folder', action='store')
        args = parser.parse_args('-b foo'.split())
        print args
        args = parser.parse_args('-b foo -f /foo'.split())
        print args
    

Gives:

    
    
    > Namespace(bucketname='foo', folder=None)
    > Namespace(bucketname='foo', folder='/foo')
    

Which means you could rewrite your function as:

    
    
    import sys
    import argparse
    
    def main():
        parser = argparse.ArgumentParser()
        parser.add_argument('-b', '--bucket', dest='bucketname', action='store')
        parser.add_argument('-f', '--folder', dest='folder', action='store')
        args = parser.parse_args()
        s3 = get_files()
        s3.foldername = args.folder
        s3.download_files()
    

Without any further work, the output of `script.py --help` is:

    
    
    usage: script.py [-h] [-b BUCKETNAME] [-f FOLDER]
    
    optional arguments:
      -h, --help            show this help message and exit
      -b BUCKETNAME, --bucket BUCKETNAME
      -f FOLDER, --folder FOLDE
    

