首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用kazoo在Python中查看子代节点?

如何使用kazoo在Python中查看子代节点?
EN

Stack Overflow用户
提问于 2013-11-20 02:18:14
回答 2查看 2.7K关注 0票数 4

我最近开始使用Python for Zookeeper。我正在为Zookeeper使用kazoo库。

我有一个使用Zookeeper的kazoo的非常简单的用例。我有一个根节点,它是- /root。现在我需要监视根节点/root,如果添加到根节点/root的新节点是/root/testing,那么我将只监视/root/testing节点。我不想监视除testing节点之外的任何其他节点。然后,如果有任何新的子节点被添加到/root/testing节点,那么我也会监视它们。

假设下面的孩子加起来-

代码语言:javascript
复制
`/root/testing/test1`

然后我也会关注test1节点。

在Zookeeper中使用Kazoo可以做到这一点吗?我只能在一个Zookeeper节点(/root)上进行监视,代码如下:

代码语言:javascript
复制
#!/usr/bin/python
import time

from kazoo.client import KazooClient

zk = KazooClient(hosts='127.0.0.1:2181')
zk.start()

########################################
@zk.ChildrenWatch("/root/testing")
def watch_children(children):
   print(children)

########################################

while True:
    time.sleep(5)

有没有人能帮我在子节点上做多个监视呢?

EN

回答 2

Stack Overflow用户

发布于 2013-11-26 05:52:08

试试这样的东西。

代码语言:javascript
复制
import time
from kazoo.client import KazooClient

zk = KazooClient(hosts='127.0.0.1:2181')
zk.start()

children = zk.get_children("/root/",)
if "/testing" in children:
    children_testing = zk.get_children("/root/testing/")
        if children_testing != []: 
            @zk.ChildrenWatch("/root/testing")
            def watch_children(children):
                print(children)
        else:
            @zk.ChildrenWatch("/root/")
            def watch_children(children):
                print(children)
while True:
    time.sleep(5)
票数 2
EN

Stack Overflow用户

发布于 2013-11-24 06:27:17

如果你试图监视多个节点,而不是一个节点,你可以使用多个线程(基本上它在不同的“线程”上同时运行不同的代码)。Python有一个用于同时执行操作的线程模块,这可能正是您想要的。下面是一个实现了线程的代码示例。

代码语言:javascript
复制
import threading

def watch_node(node):
    #implement your node watching script here

def watch_in_background(node):
    watcher = threading.Thread(target=watch_node,args=(node))   #initializes a thread that can run the watch_node function in the background, passing the node argument to it
    watcher.start()                                             #tells the thread to start running
    return watcher                                              #returns the thread object just in case you want to use it for something

watch_in_background(<node>)                                     #so this code will now watch the node in the background, allowing you to do other things, like watch multiple nodes
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20079018

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档