Search code examples
pythonparsingpython-2.7command-line-interfaceargv

How do I take unlimited sys.argv[] arguments?


To elaborate, I am interested in learning how to code out in python a sys.argv[] function that allows the user to supply as many arguments as the user wants. I am unsure on if there is a better way to do this or if it can be done at all.

The point to this is to develop a similarity tool between text docs of various size and quantity. the use case in this situation takes as little as argv[1] and as many as argv[unlimited].

Any input, sources, or advice is welcome.


Solution

  • sys.argv is just a regular Python list, so you can just ask len(sys.argv) for example, or you can just enumerate the contents directly (using a for ... in loop) as with any other iterable.

    Note that sys.argv[0] is the name of the program, so you need to skip the first item. (It then follows that (len(sys.argv) - 1) is the number of arguments supplied by the caller.)

    import sys
    
    for arg in sys.argv[1:]:
        print arg
    

    Example invocation:

    $ python test.py a b c
    a
    b
    c
    

    In your case you would replace print arg with whatever processing you wanted to do on the argument.

    This will work up to any operating-system-imposed limits. (Some OSes limit the number of arguments you can pass to a program. For example, on Linux you can see these limits with xargs --show-limits.)