Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking multiple lines of strings as command line input in Python

In coding contests, I am supplied an initialization file from which to read initial parameters. However, sometimes the parameters are spread over separate lines as follows:

x
a 
b

(All of them integers)

Now when I read line1, I believe I would store x like this:

x = int(sys.argv[1])

How do I take care of other lines? Will sys.argv[2] give me the next parameter on line 2?

More precisely, will using:

par_list = sys.argv[1:].split(" ") 

give me a list of parameters on all the lines?

like image 424
pratik_m Avatar asked Mar 19 '23 04:03

pratik_m


2 Answers

This will do the trick:

>> python program.py $(cat input.txt)

Sample program:

import sys
paras = [int(x) for x in sys.argv[1:]]
print(paras)

Sample input file:

42
-1
100

Output:

>> python program.py $(cat input.txt)
[42, -1, 100]
like image 131
timgeb Avatar answered Mar 21 '23 17:03

timgeb


I'm assuming you're passing the input filename to the python script, in cmdline.

python script.py input.txt

In which case, sys.argv[1] = 'input.txt' is to access the contents of the input file:

with open(sys.argv[1], 'r') as f:
    lines = f.readlines()

Now, lines is a list containing all the lines of data from input.txt.

like image 39
arvindch Avatar answered Mar 21 '23 17:03

arvindch