模块化开发可重用性:如何处理 While True 循环?
我最近一直在使用 pybluez 模块来扫描附近的蓝牙设备。我现在想做的是扩展程序以查找附近的 WiFi 客户端设备。
WiFi 客户端扫描仪需要有一个 While True
循环来持续监控电波。如果我将其编写为一个直接的单文件程序,那就很容易了。
import ...
while True:
client = scan()
print client['mac']
然而,我想要的是使其成为一个模块。我希望以后能够重用它,并且可能的话,让其他人也使用它。我不明白的是如何处理循环。
import mymodule
scan()
假设第一个示例代码是“mymodule”,该程序将简单地将数据打印到标准输出。我希望能够在我的程序中使用这些数据,而不是让模块将其打印出来......
我应该如何对模块进行编码?
I've been playing around with the pybluez module recently to scan for nearby Bluetooth devices. What I want to do now is extend the program to also find nearby WiFi client devices.
The WiFi client scanner will have need to have a While True
loop to continually monitor the airwaves. If I were to write this as a straight up, one file program, it would be easy.
import ...
while True:
client = scan()
print client['mac']
What I want, however, is to make this a module. I want to be able to reuse it later and, possible, have others use it too. What I can't figure out is how to handle the loop.
import mymodule
scan()
Assuming the first example code was 'mymodule', this program would simply print out the data to stdout. I would want to be able to use this data in my program instead of having the module print it out...
How should I code the module?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为最好的方法是让扫描仪在与主程序不同的线程上运行。该模块应该具有启动和停止扫描仪的方法,以及返回当前访问点列表的方法(使用锁进行同步)。请参阅线程模块。
I think the best approach is going to be to have the scanner run on a separate thread from the main program. The module should have methods that start and stop the scanner, and another that returns the current access point list (using a lock to synchronize). See the threading module.
一些非常简单的东西怎么样:
mymodule.py
othermodule.py
如果你想要比这更有用的东西,我还建议像@kindall那样使用后台线程。
How about something pretty straightforward like:
mymodule.py
othermodule.py
If you want something more useful than that, I'd also suggest a background thread as @kindall did.
两个接口会很有用。
接受回调的“发现时通知”函数。例如(也许是拼写错误,我只是即兴写下这个)。
这样做将使用:
Two interfaces would be useful.
A "notify on found" function that accepted a callback. For instance (maybe typos, i just wrote this off the cuff).
which would be used by doing this:
如果我收到您的问题,您希望将
scan()
放在一个单独的文件中,以便以后可以重复使用。创建utils.py
创建WiFi.py
If I get your question, you want
scan()
in a separate file, so that it can be reused later.Create utils.py
Create WiFi.py