简体   繁体   中英

Variable number of arguments to Python script

The command line to run my Python script is:

./parse_ms.py inputfile 3 2 2 2 

the arguments are an input, number 3 is the number of samples of my study each with 2 individuals.

In the script, I indicate the arguments as follows:

inputfile = open(sys.argv[1], "r")
nsam = int(sys.argv[2])
nind1 = int(sys.argv[3])
nind2 = int(sys.argv[4])
nind3 = int(sys.argv[5])

However, the number of samples may vary. I can have:

./parse_ms.py input 4 6 8 2 20

in this case, I have 4 samples with 6, 8, 2 and 20 individuals in each.

It seems inefficient to add another sys.argv everything a sample is added. Is there a way to make this more general? That is, if I write nsam to be equal to 5, automatically, Python excepts five numbers to follow for the individuals in each sample.

You can simply slice off the rest of sys.argv into a list. eg

inputfile = open(sys.argv[1], "r")
num_samples = int(sys.argv[2])
samples = sys.argv[3:3+num_samples]

Although if that is all your arguments, you can simply not pass a number of samples and just grab everything.

inputfile = open(sys.argv[1], "r")
samples = sys.argv[2:]

Samples can be converted to the proper datatype afterward.

Also, look at argparse for a nicer way of handling command line arguments in general.

You can have a list of ninds and even catch expections doing the following

try:
    ninds = [int(argv[i+3]) for i in range(int(argv[2]))]
except IndexError:
    print("Error. Expected %s samples and got %d" %(argv[2], len(argv[3:])))

well, you should make a list:

import sys
inputfile = open(sys.argv[1]) # the second argument is by default "r", so you don't need to put it
nsam = int(sys.argv[2])
sams = []
for i in range(3, len(nsam)):
    sams.append(sys.argv[i])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM