Marco Scannadinari
Marco Scannadinari

Reputation: 1874

Use *args without putting the arguments into a tuple?

Here is my code:

def main(*args):
    # The following code will look for arguments and record their start and
    # end positions.
    arg = False
    arg_invalid = False
    arg_start = -1
    arg_end = -1
    i = 1

    print("main args = " + str(args))

... stripped irrelevant code ...

if __name__ == "__main__":
    print("sys args = " + str(sys.argv))
    print("tuple'd args = " + str(tuple(sys.argv)))
    main(sys.argv)

And the output:

$ ./gmanager.py foo bar 128
sys args = ['./gmanager.py', 'foo', 'bar', '128']
tuple'd args = ('./gmanager.py', 'foo', 'bar', '128')
main args = (['./gmanager.py', 'foo', 'bar', '128'],)

As you can see, after main() is called, main() places its arguments into a tuple. I do not want this as it makes for complicated argument / string referencing (arg[x][y][z]).

Is there a way to accept arguments as their prior state in my main() function, or can I strip the tuple from outside my arguments?

Upvotes: 1

Views: 846

Answers (2)

nneonneo
nneonneo

Reputation: 179432

Either pass the list in directly:

def main(args):
    ...

main(sys.argv)

or use * to perform argument unpacking:

def main(*args):
    ...

main(*sys.argv)

The latter is useful for testing, as you can write e.g.

main('foo', 'arg1', 'arg2')

to simulate command-line arguments.

Upvotes: 2

Robᵩ
Robᵩ

Reputation: 168626

Since you want exactly one parameter to main(), and you want it to be a list, just get rid of the * in def main, like so:

def main(args):
  print str(args)

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

Upvotes: 1

Related Questions