我用Tornado编写了两个处理程序,HandlerFirst是一个服务器发送的事件处理程序,带有一个while循环来获取全局变量new_test 的值,我想使用HandlerSecond更改值。
我的代码如下:
new_test = 0
def update_test_flag(new_test):
print("now_value: ", new_test)
return new_test + 1
class HandlerFirst(RequestHandler):
async def get(self):
while True:
global new_test
new_test = update_test_flag(new_test)
if new_test == 0:
self.write('data:0\n\n')
self.flush()
time.sleep(2)
class HandlerSecond(RequestHandler):
async def get(self):
global new_test
print("test: ", new_test)
new_test = 0
print("test changed: ", new_test)
self.write("ok")
出局是:
now_value: 0
now_value: 1
now_value: 2
now_value: 3
now_value: 4
test: 0
test changed: 0
[2018-04-16 10:52:36,689] (tornado.access):web.py:log_request-(2063)INFO: 304 GET /dashboard/test-sse/ (192.168.0.29) 1.09ms
[2018-04-16 10:52:36,763] (tornado.access):web.py:log_request-(2063)INFO: 200 GET /favicon.ico (192.168.0.29) 3.01ms
now_value: 5
now_value: 6
test: 0
test changed: 0
[2018-04-16 10:52:41,561] (tornado.access):web.py:log_request-(2063)INFO: 304 GET /dashboard/test-sse/ (192.168.0.29) 0.45ms
[2018-04-16 10:52:41,592] (tornado.access):web.py:log_request-(2063)INFO: 200 GET /favicon.ico (192.168.0.29) 0.45ms
now_value: 7
now_value: 8
似乎while循环中的更改没有保存,我对全局变量的使用有什么问题吗?感谢您的帮助和提示。
ps:我也找到了一个没有解决方案的类似问题。 Change global variable in Python in another thread