python - file.Read() 停止程序,直到将新内容添加到文件中。如果没有新内容,如何跳过这一行?
问题描述
我正在 Linux 中编写一个 python 程序,它从系统文件中读取鼠标位置。一切正常,但是当鼠标停止(没有数据添加到文件中)时,程序在读取功能处停止并等待新数据继续进行。如果要等待,如何让程序跳过读取功能?
这是代码:
import struct
file = open( "/dev/input/mouse1", "rb" )
def getMouseEvent():
#check before reading if there is a content, since otherwise the program will stop at the next line until a new data is available (the mouse moves)
buf = file.read(3)
x,y = struct.unpack( "bb", buf[1:] )
print ("x: %d, y: %d\n" % (x, y) )
while( 1 ):
getMouseEvent()
file.close()
我想要的是这样的:
def getMouseEvent():
if(ThereIsData):
buf = file.read(3)
x,y = struct.unpack( "bb", buf[1:] )
print ("x: %d, y: %d\n" % (x, y) )
else:
print('Skipped reading')
解决方案
对于这个特定的用例,您只需将 fd 设置为非阻塞:
>>> g = open('/dev/input/mouse1', 'rb')
>>> g.read(1) # blocks here, had to C-c
^CTraceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyboardInterrupt
>>> import os; os.set_blocking(g.fileno(), False)
>>> g.read(1)
>>>
您也可以使用select
for ThereIsData
,但这本身还不够:如果有任何可用数据,则设备将被视为可读,但如果只有 1 个字节可用,则您请求 3 个字节,并且设备处于阻塞模式...它将阻塞,直到 3 个字节可用。因此,虽然它可以避免虚假读取(这很好)和忙循环(因为您可以添加超时,select
所以如果设备未准备好,实际上什么都不会发生),但这还不够。
虽然我想它可能足以满足您的需求。
推荐阅读
- ios - 带有重定向到自定义 url 方案的 iOS React Native 获取失败并出现“网络请求失败”错误
- r - 将某些列的类更改为整数
- arrays - 如何从没有结构的函数中获取多个变量?
- testng - 使用 RetryAnalyzer 时如何从范围报告中删除失败测试用例的第一次尝试
- javascript - firebase 身份验证错误:电子邮件地址格式错误
- python - TimedRotatingFileHandler 将日志保存在前一天的文件中
- python - 如何阻止单个 SQS 消息多次触发 Lambda 函数?
- anylogic - AnyLogic 路库车道选择
- javascript - 使用 js 更改下拉列表的值
- powershell - 尝试更改创建日期时拒绝访问路径