亲宝软件园·资讯

展开

python  信号库

autofelix 人气:0

一、安装

pip install blinker

二、创建发送信号

from blinker import signal
# 创建一个信号,并给信号命名
s = signal('autofelix')
def say(args):
print('我是飞兔小哥')
# 信号注册一个接收者
s.connect(say)
if "__main__" == __name__:
# 发送信号
s.send()

三、匿名信号

from blinker import signal
# 创建一个匿名信号
s = signal()
def say(args):
print('我是飞兔小哥')
# 信号注册一个接收者
s.connect(say)
if "__main__" == __name__:
# 发送信号
s.send()

四、组播信号

from blinker import signal
s = signal('autofelix')
def fans_one(args):
print(f'我是粉丝一号,我关注了: {args}')
def fans_two(args):
print(f'我是粉丝二号,我关注了: {args}')
s.connect(fans_one)
s.connect(fans_two)
if "__main__" == __name__:
s.send('飞兔小哥')

五、接受方订阅主题

from blinker import signal
s = signal('autofelix')
def fans(args):
print(f'我是个小粉丝,{args} 是我的老师')
# 信号注册一个接收者, 并指定主题
s.connect(animal, sender='飞兔')
if "__main__" == __name__:
for i in ['飞兔', '飞兔小姐姐', '飞兔小哥哥']:
s.send(i)

六、装饰器用法

from blinker import signal
s = signal('autofelix')
@s.connect
def fans_one(args):
print(f'我是粉丝一号,我关注了: {args}')
@s.connect
def fans_two(args):
print(f'我是粉丝二号,我关注了: {args}')
if "__main__" == __name__:
s.send('飞兔小哥')

七、订阅主题的装饰器

from blinker import signal
s = signal('autofelix')
@s.connect_via('飞兔')
def fans(args):
print(f'我是个小粉丝,{args} 是我的老师')
if "__main__" == __name__:
for i in ['飞兔', '飞兔小姐姐', '飞兔小哥哥']:
s.send(i)

八、检查信号是否有接收者

from blinker import signal
a1 = signal('autofelix-1')
a2 = signal('autofelix-2')
def fans(sender):
print('我是个小粉丝')
a1.connect(fans)
if "__main__" == __name__:
res = a1.receivers
print(res)
if res:
a1.send()
res = a2.receivers
print(res)
if res:
a2.send()
else:
print("我是个偶像")

九、是否订阅了某个信号

from blinker import signal
a1 = signal('autofelix-1')
a2 = signal('autofelix-2')
def fans(sender):
print('我是个小粉丝')
a1.connect(fans)
if "__main__" == __name__:
res = a1.has_receivers_for(fans)
print(res)
res = a2.has_receivers_for(fans)
print(res)

加载全部内容

相关教程
猜你喜欢
用户评论