轮询文件以了解更改是如何工作的?
问题
我希望下面的脚本最多打印一个事件,然后停止(编写它只是为了说明问题)。
#!/usr/bin/env python
from select import poll, POLLIN
filename = "test.tmp"
# make sure file exists
open(filename, "a").close()
file = open(filename, "r+")
p = poll()
p.register(file.fileno(), POLLIN)
while True:
events = p.poll(100)
for e in events:
print e
# Read data, so that the event goes away?
file.read()
但是,它每秒打印大约 70000 个事件。为什么?
背景
我编写了一个在内部使用 pyudev.Monitor 类的类。除此之外,它使用 轮询对象。
现在我正在尝试为我的类编写一个单元测试(我意识到我应该先编写单元测试,所以不需要指出它),因此我需要为我的类编写我自己的 fileno() 方法模拟 pyudev.Monitor 对象,我需要控制它,以便我可以触发 poll 对象报告事件。正如上面的代码所示,我无法让它停止报告看似不存在的事件!
我在民意调查类中找不到 recognize_event() 或类似的东西来使事件消失(我怀疑只有一个事件以某种方式卡住了),搜索谷歌,这个网站没有产生任何结果。我在 Ubuntu 10.10 上使用 python 2.6.6。
The problem
I expected the script below to print at most one event and then stop (it's written only to illustrate the problem).
#!/usr/bin/env python
from select import poll, POLLIN
filename = "test.tmp"
# make sure file exists
open(filename, "a").close()
file = open(filename, "r+")
p = poll()
p.register(file.fileno(), POLLIN)
while True:
events = p.poll(100)
for e in events:
print e
# Read data, so that the event goes away?
file.read()
However, it prints about 70000 events per second. Why?
Background
I've written a class that uses the pyudev.Monitor class internally. Amongst other things, it polls the fileno supplied by the fileno() method for changes using a poll object.
Now I'm trying to write an unit test for my class (I realize I'm supposed to write the unit test first, so no need to point it out), and therefore I need to write my own fileno() method for my mock pyudev.Monitor object, and I need to control it so that I can trigger the poll object to report an event. As the above code demonstrates, I can't make it stop reporting seemingly non-existent events!
I can find no acknowledge_event() or similar in the poll class to make the event go away (I suspect there's just one event that's somehow stuck), searching google and this site has yielded nothing. I'm using python 2.6.6 on Ubuntu 10.10.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用管道而不是文件会更幸运。试试这个:
这将打印出您正在寻找的单个事件。要触发 poll 事件,您所要做的就是向可写文件描述符写入一个字节。
You'll have better luck using pipes rather than files. Try this instead:
This will print out the single event you're looking for. To trigger the poll event, all you have to do is write a byte to the writeable file descriptor.