所以我看起來像這樣叫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'不能像普通文件那樣打開。 –