1

所以我看起来像这样叫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]) 
+0

什么是你所得到的错误?我怀疑'sys.stdin'不能像普通文件那样打开。 –

回答

3

sys.stdin是一个已经打开的(用于读取)文件。不是文件名:

>>> import sys 
>>> sys.stdin 
<open file '<stdin>', mode 'r' at 0x7f817e63b0c0> 

因此,您可以将它与文件对象api一起使用。

你可以尝试这样的事:

if (len(sys.argv) == 1): 
    fobj = sys.stdin 
else: 
    fobj = open(sys.argv[-1], 'r') # command-line argument 

# ... use file object 
+0

那么,我该如何实现我的if-else,因此我不必在每个if和else块内部放置整个语句? else块可以在它下面有完全相同的代码,但if块只需要:对于sys.stdin中的行和其余 – PTN

相关问题