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?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
CQM
  • 42,592
  • 75
  • 224
  • 366
  • 1
    If the `main` function takes an `argv` parameter, it should probably _use_ that parameter, rather than ignoring it and using `sys.argv` instead… – abarnert Sep 25 '13 at 23:13
  • 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. – abarnert Sep 25 '13 at 23:14
  • @abarnert I have an else – CQM Sep 25 '13 at 23:15

2 Answers2

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)
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
2

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

jhermann
  • 2,071
  • 13
  • 17
  • I've used that before, what is the benefit between it and sys.argv or using optparse vs something else – CQM Sep 26 '13 at 00:24
  • 1
    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. – jhermann Sep 26 '13 at 07:04