Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python file.Read()停止程序,直到向文件中添加新内容。如果没有新内容,如何跳过此行?_Python_File - Fatal编程技术网

Python file.Read()停止程序,直到向文件中添加新内容。如果没有新内容,如何跳过此行?

Python file.Read()停止程序,直到向文件中添加新内容。如果没有新内容,如何跳过此行?,python,file,Python,File,我正在Linux中编写一个python程序,从系统文件中读取鼠标位置。一切工作正常,但当鼠标停止(没有数据添加到文件中)时,程序在读取功能处停止,并等待新数据继续。如果要等待,如何让程序跳过读取函数 代码如下: import struct file = open( "/dev/input/mouse1", "rb" ) def getMouseEvent(): #check before reading if there is a

我正在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)#这里的块,必须C-C
^CTraceback(最近一次通话最后一次):
文件“”,第1行,在
键盘中断
>>>导入操作系统;os.set_阻塞(g.fileno(),False)
>>>g.read(1)
>>>
您也可以使用for
ThereIsData
,但是这本身是不够的:如果有任何可用数据,设备将被视为可读的,但是如果只有1个可用字节,则您请求3个,并且设备处于阻塞模式。。。它将一直阻塞,直到有3个字节可用。因此,虽然它可以避免频繁的读取(这很好)和繁忙的循环(因为您可以为
选择
添加一个超时,因此如果设备没有准备好,实际上什么也不会发生),但这还不够

不过我想这可能足够满足你的需要了