python command line arguments in main, skip script name
Asked Answered
E

2

20

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?

Eldreeda answered 25/9, 2013 at 23:10 Comment(3)
If the main function takes an argv parameter, it should probably use that parameter, rather than ignoring it and using sys.argv instead…Pugilism
Also, you don't need the if check at all. If there are no arguments, the loop will successfully run 0 times, so let it do so.Pugilism
@Pugilism I have an elseEldreeda
T
31

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)
Token answered 25/9, 2013 at 23:12 Comment(0)
P
2

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

Publication answered 25/9, 2013 at 23:31 Comment(2)
I've used that before, what is the benefit between it and sys.argv or using optparse vs something elseEldreeda
It's the thing to use for arg parsing (unless you need cliff). It has a great API. It's not deprecated like optparse. It standardizes the look+feel of your script.Publication

© 2022 - 2024 — McMap. All rights reserved.