在Python中将多行字符串作为命令行输入(Taking multiple lines of strings as command line input in Python)

在编码竞赛中,我提供了一个初始化文件,从中读取初始参数。 但是,有时参数分布在不同的行上,如下所示:

x

a

b

(所有这些整数)

现在,当我读取line1时,我相信我会像这样存储x :

x = int(sys.argv[1])

我该如何处理其他线路? sys.argv[2]会给我第2行的下一个参数吗?

更准确地说,将使用:

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

给我一个关于所有线路的参数列表?

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?



满意答案

这样就可以了:

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

示例程序:

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

示例输入文件:

42

-1

100

输出:

>> python program.py $(cat input.txt)
[42, -1, 100]
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]
2014-06-28