sys.stdin在ctrl-d上不关闭 [英] sys.stdin does not close on ctrl-d

查看:641
本文介绍了sys.stdin在ctrl-d上不关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 来自sys import stdin 
for line in stdin:
打印行



我运行,输入行,然后按 Ctrl < kbd> + D ,但程序不退出。



这样工作:

  $ printfecho| python program.py 

为什么当我按下 Ctrl + d
我使用的是Fedora 18终端。

解决方案

Ctrl + < 有一个奇怪的效果。它不关闭输入流,但只导致C级别 fread()返回空结果。对于常规文件,这样的结果意味着该文件现在处于结束,但是可以阅读更多,例如。



此外,还有缓冲的问题 - 其中三个级别!




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


  • C级stdin文件默认具有行缓冲区。


  • 终端本身(!)在默认模式(熟食模式)下,在将数据发送到进程之前读取一行数据,这解释了为什么键入 Ctrl



$ b p>这个例子避免了第一个问题,这是所有你需要,如果你想要的是检测 Ctrl + D 键入作为其自己的行:

  import sys 

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

你得到每一行最后的'\\\
' / code>,除了line来自于 Ctrl + D ,在这种情况下你只需要 / code>(但是继续阅读,除非我们添加 if line =='':break )。


I have the following code in 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.

This does work:

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

In addition, there are issues of buffering --- three levels of them!

  • Python's iteration over a file does block buffering. Avoid it to read from interactive streams.

  • the C-level stdin file has, by default, a line buffer.

  • 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).

这篇关于sys.stdin在ctrl-d上不关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆