Skip to main content
 首页 » 编程设计

Python:一次两个循环

2024年11月01日13虾米姐

这个问题已经解决了!

我遇到了一个问题:我是 Python 的新手,我想执行多个循环。我想运行一个 WebSocket 客户端 (Autobahn),我想运行一个循环来显示在特定文件夹(pyinotify 或 Watchdog)中编辑的文件。

两者都在永远运行,太好了。有没有办法在我运行 FileSystemWatcher 时立即运行它们并通过 WebSocket 连接发送消息,例如回调、多线程、多处理或只是单独的文件?

    factory = WebSocketClientFactory("ws://localhost:8888/ws", debug=False) 
    factory.protocol = self.webSocket 
    connectWS(factory) 
    reactor.run() 

如果我们运行它,它就会成功。但是如果我们运行这个:

    factory = WebSocketClientFactory("ws://localhost:8888/ws", debug=False) 
    factory.protocol = self.webSocket 
    connectWS(factory) 
    reactor.run() 
 
    # Websocket client running now,running the filewatcher      
 
    wm = pyinotify.WatchManager() 
 
    mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE  # watched events 
 
    class EventHandler(pyinotify.ProcessEvent): 
        def process_IN_CREATE(self, event): 
            print "Creating:", event.pathname 
 
        def process_IN_DELETE(self, event): 
            print "Removing:", event.pathname 
    handler = EventHandler() 
    notifier = pyinotify.Notifier(wm, handler) 
    wdd = wm.add_watch('/tmp', mask, rec=True) 
    notifier.loop() 

这将创建 2 个循环,但由于我们已经有一个循环,所以“reactor.run()”之后的代码根本不会运行。

供您引用:此项目将成为一个同步客户端。

非常感谢!

编辑:有错误。 ( http://pastebin.com/zHNG2c6U ) 我现在不知道该怎么办..

webSocket 类:

class webSocket(WebSocketClientProtocol): 
    def sendHello(self): 
        pass 
 
    def onOpen(self): 
        self.sendHello() 
 
    def onMessage(self, msg, binary): 
        print "Got echo: " + msg 
        reactor.callLater(1, self.sendHello) 
 
    def notify(ignore, filepath, mask): 
        print "CALLBACK" 
        #print "event %s on %s" % (', '.join(inotify.humanReadableMask(mask)), filepath) 

edit2:你可以在这里看到完整的代码:http://pastebin.com/iHKRcLVA

最终编辑: 大家,谢谢给我回复!将回调“def”置于类之外效果很好!

请您参考如下方法:

Autobahn 建立在 Twisted 之上,这是一个异步应用程序框架。您不需要显式线程来使这一切正常工作。您可以改为使用 twisted.internet.inotify 实现 FileSystemWatcher 类(有一个例子 here )。

我不知道这两个组件如何相互通信,因为我已经很多年没有使用 Twisted 了。但是有一个桥接串口的例子here .