Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable number of arguments to Python script

Tags:

python

input

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.

like image 972
Homap Avatar asked Aug 15 '26 05:08

Homap


1 Answers

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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!