标准输入未按预期工作 [Python]

Stdin Not Working As Intended [Python]

我正在 运行 通过 Python 中的一些练习,包括一个可以从命令行或标准输入获取输入的简单行计数器:

#### line_count1.py ####

import sys

def count_lines(file):
    n = 0
    for line in file:
        n = n + 1
    return n

if len(sys.argv) == 1:
    print("Needs stdin")
    file = sys.stdin
else:
    print("File given at command line")
    file = open(sys.argv[1])

print (count_lines(file))

如果我在命令行输入一个文件,即 python line_count1.py file_with_4_lines.txt,效果很好,我得到了输出:

File given at command line
4

但是,如果我输入它以便它通过 python line_count1.py 确实需要标准输入,我会得到以下输出:

Needs stdin
_

但实际上从未对我的 stdin 条目做任何事情。我可以输入 file_with_4_lines.txt,但它只是接受它并等待我输入另一行标准输入,直到我必须终止任务管理器中的代码时才会中断。

什么会导致这种情况发生?根据我的理解,只要我为 stdin 输入一些内容,就会触发其余代码通过。但事实并非如此。我错过了什么?

这与您的代码无关,但与终端上的 stdin 读取行为有关。有关详细信息,请参阅以下 post:https://unix.stackexchange.com/questions/16333/how-to-signal-the-end-of-stdin-input

编辑: 正如@Chase 所说,在 window 上终止标准输入的关键是 Ctrl+Z,而在 linux 上是 Ctrl+D.

听起来你想接受来自 stdin 的文件名,如果没有在命令行中给出,而你现在正在做的是试图计算 stdin 本身。

如果目标是处理给定文件,其中名称来自 stdin 或命令行,则代码应更改为:

if len(sys.argv) == 1:
    # Prompt for and read a single line from stdin to get the desired file name
    filename = input("Needs stdin")  # On Py2, use raw_input, not input
else:
    print("File given at command line")
    # Use argument as filename
    filename = sys.argv[1]

# Open the name provided at stdin or command line
# Use with statement so it's properly closed when you're done
with open(filename) as file:
    print(count_lines(file))