Reputation: 183
I'm attempting to pass in an argument to my script but for some reason if I specify -t
for my time value, it shows up in the script as an empty string. If I specify --time
, I get the correct value. Why?
import sys, getopt, time
def main(argv):
inputfile = ''
outputfile = ''
sleeptime = 6
if len(sys.argv) == 1:
print("No arguments supplied")
print('Usage: test.py -i <inputfile> -o <outputfile> -t <1-24>')
sys.exit()
try:
opts, arg = getopt.getopt(argv, "i:o:t", ["ifile=", "ofile=", "time="])
except getopt.GetoptError:
print('Incorrect options.')
print('Usage: test.py -i <inputfile> -o <outputfile> -t <1-24>')
sys.exit()
for opt, arg in opts:
if opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
elif opt in ("-t", "--time"):
print("time = ", arg)
sleeptime = int(arg)
else:
print("Unknown arg")
sys.exit()
print(sleeptime)
if __name__ == "__main__":
main(sys.argv[1:])
I pretty much ripped the code from here: https://www.tutorialspoint.com/python/python_command_line_arguments.htm
Upvotes: 2
Views: 1894
Reputation: 1389
To answer your question, i think you forgot the trailing colon for the t
option (since t
requires an argument), try changing it to "i:o:t:"
, see https://docs.python.org/3/library/getopt.html#getopt.getopt.
The whole line should look like this:
opts, arg = getopt.getopt(argv, "i:o:t:", ["ifile=", "ofile=", "time="])
In general i agree with the comments above though, i would recommend to use https://docs.python.org/3/library/argparse.html for command line argument parsing :).
Upvotes: 5
Reputation: 363486
In the docs:
shortopts is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon
You missed the colon on the t
. Modify like this, and it works:
opts, arg = getopt.getopt(argv, "i:o:t:", ["ifile=", "ofile=", "time="])
Upvotes: 2