Reputation: 2214
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.
Upvotes: 1
Views: 5016
Reputation:
You can simply slice off the rest of sys.argv
into a list. e.g.
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.
Upvotes: 8
Reputation: 744
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:])))
Upvotes: 0