Python中奇怪的select.select()行为

2024-04-25 13:27:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python脚本逐个字符地读取stdin,使用select.select()在有可用内容时得到通知。我面对的是一种我不明白的行为;最好用一个例子来说明。首先,这里是一个示例选择代码:

import select
import sys

while True:
    r, w, e = select.select([sys.stdin], [], [])
    print "Read: %s" % sys.stdin.read(1)

下面是脚本的运行示例:

/tmp$ python test.py 
AAAA     # I type in a few chars then ENTER.
Read: A  # Only one char is detected :(
BBBB     # I type in more characters
Read: A  # Now all the previous characters are detected!?
Read: A
Read: A
Read:    # ('\n' is read which I want)

Read: B  # Wait, where are the other Bs?
CCCC     # I need to type more chars so that BBB is printed, and the first C.

如上所述,如果在stdin中键入多个字符,则只打印第一个字符。然后,如果添加了更多字符,则会打印以前输入的所有剩余字符以及新输入的第一个字符

我做错什么了


Tags: theinimport脚本示例readistype
1条回答
网友
1楼 · 发布于 2024-04-25 13:27:21

select.select不知道Python文件对象(如sys.stdin)中的缓冲。您可以完全绕过file对象,尽管这会与试图从sys.stdin读取的尝试发生奇怪的交互:

import select
import os
import sys

while True:
    r, w, e = select.select([sys.stdin], [], [])
    print os.read(sys.stdin.fileno(), 1)

相关问题 更多 >