python command line arguments in main, skip script name

拈花ヽ惹草 提交于 2019-12-19 05:18:26

问题


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

I want it to skip myscript.py and simply run commandlineargument through commandlineargument(n)

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


回答1:


Since sys.argv is a list, you can use slicing 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.argv is more than 1 and throw an error if it doesn't, for example:

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

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



回答2:


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



来源:https://stackoverflow.com/questions/19016702/python-command-line-arguments-in-main-skip-script-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!