2

I have a program which provides a command line input like this:

python2.6 prog.py -p a1 b1 c1

Now, we can have any number of input parameters i.e. -p a1 and -p a1 c1 b1 e2 are both possibilities.

I want to create a tuple based on the variable input parameters. Any suggestions on how to do this would be very helpful! A fixed length tuple would be easy, but I am not sure how to implement a variable length one.

thanks.

user308827
  • 21,227
  • 87
  • 254
  • 417
  • do you know the 'sys' package ? it should be pretty easy to do what you need with sys.argv (see http://docs.python.org/library/sys.html) – Manuel Salvadores Nov 16 '10 at 16:31

8 Answers8

2

A tuple is fixed in length. Once you create a tuple, you can't modify it.

The command line arguments are stored in a list.

import sys
t = tuple(sys.argv[1:]) # since sys.argv[0] is the name of the script
user225312
  • 126,773
  • 69
  • 172
  • 181
1

This should do it:

import sys
t = tuple(sys.argv)

Since maybe you don't want the script name, then you might want to do this:

if len(sys.argv) > 1:
    t = tuple(sys.argv[1:])
Todd
  • 5,999
  • 2
  • 21
  • 21
  • If `len(l) < n`, `l[n-1:]` will give `[]`. And `tuple([])` is the 0-ary tuple, `()`. -> no need for this check. –  Nov 16 '10 at 16:42
1

Iterate through sys.argv until you reach another flag.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

You can transform lists into tuples using the tuple() constructor:

>>> tuple([1, 2, 3, 4])
(1, 2, 3, 4)

Use this on sys.argv =), or a slice of it. Cheers!

salezica
  • 74,081
  • 25
  • 105
  • 166
1

Why don't you look at the *args and **kwargs discussion a while back?

Community
  • 1
  • 1
Michael Shopsin
  • 2,055
  • 2
  • 24
  • 43
1
import sys

t1 = tuple(sys.argv)
t2 = tuple(sys.argv[1:])

print t1
print t2
daniels
  • 18,416
  • 31
  • 103
  • 173
1

You can get the args from the command line using getopt. It returns a list of the args, which you can then turn into a tuple using tuple()

import getopt
import sys

def main(argv):
    opts, args = getopt.getopt(argv, 'p')
    return tuple(args)
if __name__=='__main__':
    main(sys.argv[1:])

See http://www.faqs.org/docs/diveintopython/kgp_commandline.html

Herks
  • 497
  • 4
  • 6
1

The correct answer to your exact question is tuple(sys.argv[1:]), but there are better ways to get the command line arguments so you can use them more appropriately. Try optparse : http://www.doughellmann.com/PyMOTW/optparse/

If you're using Python 2.7 you should use argparse.

vonPetrushev
  • 5,457
  • 6
  • 39
  • 51