Python 当EOF联机时停止

Python 当EOF联机时停止,python,input,Python,Input,我使用以下代码逐行阅读: for line in sys.stdin: print('Output: ', end='') print(line.rstrip('\n')) 当我输入时,我会看到如下输出: test Output: test another test Output: another test eof at end of line^DOutput: eof at end of line I can still type here Output: I can sti

我使用以下代码逐行阅读:

for line in sys.stdin:
    print('Output: ', end='')
    print(line.rstrip('\n'))
当我输入时,我会看到如下输出:

test
Output: test
another test
Output: another test
eof at end of line^DOutput: eof at end of line
I can still type here
Output: I can still type here
...
在本例中,
^D
表示键入CTRL-D或EOF字符

我的程序应该在EOF出现在行尾时结束,而不仅仅是当EOF是行中的唯一字符时。我怎样才能得到这种行为

示例行为:

test
Output: test
another test
Output: another test
eof at end of line^DOutput: eof at end of line
[program terminates]

您没有提到您的操作系统,但我敢打赌它是LINUX或其他UNIX变体

这里的诀窍是^D本身并不是EOF标记。相反,读取输入的驱动程序将^D标识为文件结束的信号,从而关闭将终端连接到程序的文件,从而产生EOF条件


不过,更重要的是,当^D是行中的第一个字符时,驱动程序只解释^D,以防有人真的想输入^D。因此,这将很难做到,但这并不是程序中有问题——你只是看到了意外但正常的行为。

你没有提到你的操作系统,但我敢打赌它是LINUX还是其他UNIX变体

这里的诀窍是^D本身并不是EOF标记。相反,读取输入的驱动程序将^D标识为文件结束的信号,从而关闭将终端连接到程序的文件,从而产生EOF条件


不过,更重要的是,驱动程序只在^D是行中的第一个字符时解释它,以防有人真的想输入^D。因此,这将很难做到,但这并不是程序中有问题——您只是看到意外但正常的行为。

终端驱动程序没有关闭流,而且它总是解释
^D
。但是它只是使
read(2)
返回,当它返回0时,这只意味着EOF。有什么方法可以实现我想要的行为吗?我知道在C语言中,我可以使用类似
的东西while(getline(&line,&n,stdin)!=-1)
,这将产生我预期的行为。终端驱动程序不会关闭流,它总是解释
^D
。但是它只是使
read(2)
返回,当它返回0时,这只意味着EOF。有什么方法可以实现我想要的行为吗?我知道在C语言中,我可以使用
while(getline(&line,&n,stdin)!=-1)
,这将产生我预期的行为。