如果没有命令行参数,请阅读 stdin Python



所以我有一个名为ids的文本文件,看起来像这样:

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是一个已经打开的(用于读取)文件。不是文件名:

>>> 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

最新更新