2016-10-10 74 views
0

我想與關鍵如何獲取龍捲風對象?

龍捲風對象的值。這是我的代碼:

beanstalk = beanstalkt.Client(host='host', port=port) 
beanstalk.connect() 
print("ok1") 

beanstalk.watch('contracts') 
stateTube = beanstalk.stats_tube('contracts', callback=show) 
print("ok2") 

ioloop = tornado.ioloop.IOLoop.instance() 
ioloop.start() 

print("ok3") 

這是函數`顯示()``

def show(s): 
    pprint(s['current-jobs-ready']) 
    ioloop.stop 

當我看在我發現這個文件: enter image description here

而當我優先考慮這段代碼時,我有這樣的:

ok1 
ok2 
3 

事實上,我有我想要的結果「3」,但我不明白爲什麼我的程序繼續運行?爲什麼ioloop不關閉?我編譯時沒有ok3我該怎麼辦才能關閉ioloop並有ok3

+0

你有一個'Future'對象。請顯示您試圖稱之爲 –

+0

@ cricket_007的龍捲風代碼,我已更新我的帖子 – wxcvbn

回答

2

beanstalk.stats_tube是異步的,它返回一個Future它代表未來的結果尚未解決。

由於the README says,您的回調show將執行一個包含解析結果的字典。所以,你可以定義show,如:

def show(stateTube): 
    pprint(stateTube['current-job-ready']) 

beanstalk.stats_tube('contracts', callback=show) 

from tornado.ioloop import IOLoop 
IOLoop.current().start() 

請注意,您通過show,不show():你傳遞函數本身,而不是調用函數並傳遞它的返回值。

另一種方式來解決未來,除了傳遞一個回調,是一個協程使用它:

from tornado import gen 
from tornado.ioloop import IOLoop 

@gen.coroutine 
def get_stats(): 
    stateTube = yield beanstalk.stats_tube('contracts') 
    pprint(stateTube['current-job-ready']) 

loop = IOLoop.current() 
loop.spawn_callback(get_stats) 
loop.start() 
+0

我已編輯我的帖子。我嘗試做第一種方法,但我遇到了一些問題... – wxcvbn

+0

沒關係,我找到了解決方案!非常感謝 ! – wxcvbn

+0

我發佈了一個關於異常的新問題到回調:[here](http://stackoverflow.com/questions/39974225/tornado-how-to-return-error-exception)你能幫助我嗎? – wxcvbn