Search code examples
pythoncommand-linegetopt

Variables not saved using getopt for command line options (python)


I am trying to create a program in python and my biggest problem is getting it to use command line options to assign the variables in the program. I have been using getopt and it will print from where I define it, but the variables can not be called upon outside of the definition so that I can use for the rest of my program.

In the code below, the print state for the "Is the following correct" comes out fine but if I try to print the gender or any other variable after the code, I just get an error that it isn't defined.

By the way, the options I run are: spice.py -g m -n 012.345.6789 -r 23 -e 13 -o voicemail.mp3

Code:

import sys
import getopt


def main(argv):
    gender = 'missing'
    phone = 'missing'
    reasons = 'missing'
    endings = 'missing'
    output = 'missing'
    try:
        opts, args = getopt.getopt(argv, "hg:n:r:e:o:")
    except getopt.GetoptError:
        print 'spice.py -g <gender> -n <phone number> -r <reasons> -e <endings> -o <output name>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'test.py -i <inputfile> -o <outputfile>'
            sys.exit()
        elif opt in ("-g"):
            gender = arg
        elif opt in ("-n"):
            phone = arg
        elif opt in ("-r"):
            reasons = arg
        elif opt in ("-e"):
            endings = arg
        elif opt in ("-o"):
            output = arg
    print "Is the following correct? " + "Gender: " + gender + ", " + "Phone Number: " + phone + ", " + "Reasons: " + reasons + ", " + "Endings: " + endings + ", " + "Output: " + output


if __name__ == "__main__":
    main(sys.argv[1:])
print gender

Solution

  • in your code, gender is not global. it's only in context within the function.

    as proof, change the first couple of lines to:

    import sys
    import getopt
    gender = 'missing'
    
    def main(argv):
        global gender
    # ... all the same
    # ... below here
    

    and you'll now see that it prints (assuming it was working in context as you describe).

    when you refactor you'll actually want to either write functions that return the values you want to use and then use them or create global variables and clean up the code a bit.