首页 > 解决方案 > 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')

标签: pythonfile

解决方案


对于这个特定的用例,您只需将 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)
>>>

您也可以使用selectfor ThereIsData,但这本身还不够:如果有任何可用数据,则设备将被视为可读,但如果只有 1 个字节可用,则您请求 3 个字节,并且设备处于阻塞模式...它将阻塞,直到 3 个字节可用。因此,虽然它可以避免虚假读取(这很好)和忙循环(因为您可以添加超时,select所以如果设备未准备好,实际上什么都不会发生),但这还不够。

虽然我想它可能足以满足您的需求。


推荐阅读