main中的python命令行参数,跳过脚本名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19016702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:33:38  来源:igfitidea点击:

python command line arguments in main, skip script name

pythonfor-loopcommand-line-argumentsargvsys

提问by CQM

This is my script

这是我的脚本

def main(argv):
    if len(sys.argv)>1:
        for x in sys.argv:
            build(x)

if __name__ == "__main__":
    main(sys.argv)

so from the command line I write python myscript.py commandlineargument

所以从命令行我写 python myscript.py commandlineargument

I want it to skip myscript.pyand simply run commandlineargumentthrough commandlineargument(n)

我希望它跳过myscript.py和简单的运行commandlineargument通过commandlineargument(n)

so I understand that my for loop doesn't account for this, but how do I make it do that?

所以我知道我的 for 循环没有考虑到这一点,但我如何让它做到这一点?

采纳答案by alecxe

Since sys.argvis a list, you can use slicing sys.argv[1:]:

由于sys.argv是一个列表,您可以使用切片sys.argv[1:]

def main(argv):
    for x in argv[1:]:
        build(x)

if __name__ == "__main__":
    main(sys.argv)

But, if you can only have one script parameter, just get it by index: sys.argv[1]. But, you should check if the length of sys.argvis more than 1 and throw an error if it doesn't, for example:

但是,如果您只能有一个脚本参数,则只需通过 index: 获取它sys.argv[1]。但是,您应该检查的长度sys.argv是否大于 1,如果不是则抛出错误,例如:

def main(argv):
    if len(argv) == 1:
        print "Not enough arguments"
        return
    else:
        build(argv[1])

if __name__ == "__main__":
    main(sys.argv)

回答by jhermann

The real answer is to learn about and use argparse, though.

不过,真正的答案是了解和使用argparse