命令行参数显示为空字符串

时间:2017-11-05 17:29:34

标签: python python-3.x

我正在尝试将参数传递给我的脚本,但出于某种原因,如果我为我的时间值指定-t,它会在脚本中显示为空字符串。如果我指定--time,我会得到正确的值。为什么呢?

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:])

我几乎从这里撕掉了代码:https://www.tutorialspoint.com/python/python_command_line_arguments.htm

2 个答案:

答案 0 :(得分:3)

要回答您的问题,我认为您忘记了t选项的尾随冒号(因为t需要参数),请尝试将其更改为"i:o:t:",请参阅{{3} }。

整行应如下所示:

opts, arg = getopt.getopt(argv, "i:o:t:", ["ifile=", "ofile=", "time="])

总的来说,我同意上面的评论,但我建议使用https://docs.python.org/3/library/getopt.html#getopt.getopt进行命令行参数解析:)。

答案 1 :(得分:2)

docs

  

shortopts 是脚本想要识别的选项字母字符串,其中的选项需要参数后跟冒号

你错过了t上的冒号。像这样修改,它可以工作:

opts, arg = getopt.getopt(argv, "i:o:t:", ["ifile=", "ofile=", "time="])
相关问题