我需要在代码中处理信号,并且我使用全局来在函数之间共享状态:
exit = False
def setup_handler():
signal.signal(signal.SIGTERM, handler)
def handler(num, frame):
global exit
exit = True
def my_main():
global exit
while not exit:
do_something()
if __name__ == '__main__':
setup_handler()
my_main()
在这种情况下,有没有办法避免全局变量?在这种情况下,分享国家的最佳方式是什么?
答案 0 :(得分:6)
你可以使用一个类来封装模块全局,但它是否值得做,取决于你真正想要避免全局的程度。
class EventLoop(object):
def __init__(self):
self.exit = False
def run(self):
while not self.exit:
do_something()
def handler(self):
self.exit = True
# It's up to you if you want an EventLoop instance
# as an argument, or just a reference to the instance's
# handler method.
def setup_handler(event_loop):
signal.signal(signal.SIGTERM, event_loop.handler)
if __name__ == '__main__':
loop = EventLoop()
setup_handler(loop)
loop.run()