user308827
user308827

Reputation: 21961

Python: Create a tuple from a command line input

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.

Upvotes: 2

Views: 5907

Answers (8)

vonPetrushev
vonPetrushev

Reputation: 5599

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.

Upvotes: 1

Herks
Herks

Reputation: 505

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

Upvotes: 1

daniels
daniels

Reputation: 19203

import sys

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

print t1
print t2

Upvotes: 1

user225312
user225312

Reputation: 131627

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

Upvotes: 2

Michael Shopsin
Michael Shopsin

Reputation: 2138

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

Upvotes: 1

salezica
salezica

Reputation: 76909

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!

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

Iterate through sys.argv until you reach another flag.

Upvotes: 1

Todd
Todd

Reputation: 6169

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:])

Upvotes: 1

Related Questions