sys.stdin 不会在 ctrl-d 上关闭

2024-02-26

我在program.py中有以下代码:

from sys import stdin
for line in stdin:
    print line

I run, enter lines, and then press Ctrl+D, but the program does not exit.

这确实有效:

$ printf "echo" | python program.py 

Why does the program not exit when I press Ctrl+d? I am using the Fedora 18 terminal.


Ctrl+D has a strange effect. It doesn't close the input stream, but only causes a C-level fread() to return an empty result. For regular files such a result means that the file is now at its end, but it's acceptable to read more, e.g. to check if someone else wrote more data to the file in the meantime.

另外,还有缓冲的问题——三个级别!

  • Python 对文件的迭代确实会阻塞缓冲。避免它从交互式流中读取。

  • 默认情况下,C 级标准输入文件有一个行缓冲区。

  • the terminal itself(!), in its default mode ("cooked mode"), reads one line of data before sending it to the process, which explains why typing Ctrl+D doesn't have any effect when typed in the middle of a line.

This example avoids the first issue, which is all you need if all you want is detecting Ctrl+D typed as its own line:

import sys

while True:
   line = sys.stdin.readline()
   print repr(line)

You get every line with a final '\n', apart from when the "line" comes from a Ctrl+D, in which case you get just '' (but reading continues, unless of course we add if line == '': break).

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

sys.stdin 不会在 ctrl-d 上关闭 的相关文章

随机推荐