所以我看起来像这样叫IDS的文本文件:如果没有命令行参数,读取标准输入的Python
15 James
13 Leon
1 Steve
5 Brian
我的Python程序(id.py)应该读取文件名称作为命令行参数,将所有内容放在ID为键的字典中,并打印输出按ID进行数字排序。这是预期的输出:
1 Steve
5 Brian
13 Leon
15 James
我得到了它的这一部分工作(调用终端python id.py ids
)。但是,现在我应该检查是否没有参数,它将读取stdin
(例如,python id.py < ids
),并最终打印出相同的预期输出。然而,它在这里崩溃。这是我的程序:
entries = {}
file;
if (len(sys.argv) == 1):
file = sys.stdin
else:
file = sys.argv[-1] # command-line argument
with open (file, "r") as inputFile:
for line in inputFile: # loop through every line
list = line.split(" ", 1) # split between spaces and store into a list
name = list.pop(1) # extract name and remove from list
name = name.strip("\n") # remove the \n
key = list[0] # extract id
entries[int(key)] = name # store keys as int and name in dictionary
for e in sorted(entries): # numerically sort dictionary and print
print "%d %s" % (e, entries[e])
什么是你所得到的错误?我怀疑'sys.stdin'不能像普通文件那样打开。 –