【发布时间】:2012-07-20 10:06:23
【问题描述】:
背景:
我熟悉 C 的 select() 函数。我一直在将此功能用于许多目的。其中大多数(如果不是全部)用于读取和写入管道、文件等。我必须说我从未使用过错误列表,但这不涉及关键问题。
问题:
Python 的select() 的行为是否如下?
在我看来,尽管 straightforward 与 C select() 有接口,但 Python 上的 select() 的行为方式有所不同。 select() 似乎在文件第一次准备好读取时返回。如果您在读取文件时留下一些要读取的字节,则调用 select() 将阻塞。但是,如果您在先前对 select() 的调用返回后再次调用 select(),而这两个调用之间没有任何读取调用,select() 将按预期返回。例如:
import select
# Open the file (yes, playing around with joysticks)
file = open('/dev/input/js0', 'r')
# Hold on the select() function waiting
select.select([file], [], [])
# Say 16 bytes are sent to the file, select() will return.
([<open file '/dev/input/js0', mode 'r' at 0x7ff2949c96f0>], [], [])
# Call select() again, and select() will indeed return.
select.select([file], [], [])
([<open file '/dev/input/js0', mode 'r' at 0x7ff2949c96f0>], [], [])
# read 8 bytes. There are 8 bytes left for sure. Calling again file.read(8) will empty the queue and would be pointless for this example
file.read(8)
'<\t\x06\x01\x00\x00\x81\x01'
# call select() again, and select() will block
select.select([file], [], [])
# Should it block? there are 8 bytes on the file to be read.
如果这是 Python 中 select() 的行为,我可以接受,我可以处理。虽然不是我所期望的,但还好。我知道我能用它做什么。
但如果这不是select() 的行为,我会很感激有人告诉我我做错了什么。我读到的关于select() 的内容是Python 文档所说的:“如果读|写|错误列表中的任何文件准备好读|写|错误,则select() 返回。”。没关系,那里没有谎言。也许问题应该是:
- 何时认为文件已准备好在 python 中读取?
- 是指一个从未被读取过的文件吗?
- 是不是表示要读取字节的文件?
【问题讨论】: