背景:
我熟悉C语言的select()
函数,已经在许多场合使用过它。其中大部分是用于读写管道、文件等操作。我必须说,我从未使用过错误列表,但这与关键问题无关。
问题:
Python的select()
是否表现如下?
对我而言,尽管Python的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中什么情况下认为一个文件已经准备好进行读取?
- 这意味着从未读取过的文件吗?
- 这意味着有待读取字节的文件吗?
open()
就可以了,这对我来说很有意义。没有必要将文件描述符设置为非阻塞,也不需要更改读取模式。这样更好,因为在读取后需要将字符串unpack()
成结构体。 - Sebastian