流,我成功地使用下面的代碼,聽取他們對帳戶的直接消息流:的Python Tweepy使用Python 2.7的多任務處理
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy import API
from tweepy.streaming import StreamListener
# These values are appropriately filled in the code
consumer_key = '######'
consumer_secret = '######'
access_token = '######'
access_token_secret = '######'
class StdOutListener(StreamListener):
def __init__(self):
self.tweetCount = 0
def on_connect(self):
print("Connection established!!")
def on_disconnect(self, notice):
print("Connection lost!! : ", notice)
def on_data(self, status):
print("Entered on_data()")
print(status, flush = True)
return True
# I can add code here to execute when a message is received, such as slicing the message and activating something else
def on_direct_message(self, status):
print("Entered on_direct_message()")
try:
print(status, flush = True)
return True
except BaseException as e:
print("Failed on_direct_message()", str(e))
def on_error(self, status):
print(status)
def main():
try:
auth = OAuthHandler(consumer_key, consumer_secret)
auth.secure = True
auth.set_access_token(access_token, access_token_secret)
api = API(auth)
# If the authentication was successful, you should
# see the name of the account print out
print(api.me().name)
stream = Stream(auth, StdOutListener())
stream.userstream()
except BaseException as e:
print("Error in main()", e)
if __name__ == '__main__':
main()
這是偉大的,當我收到我還可以執行代碼一條消息,但是我添加到工作隊列中的工作需要能夠在一段時間後停止。我使用一個流行的start = time.time()並減去當前時間來確定流逝的時間,但是這個流式代碼不會循環來檢查時間。我只是在等待一個新的消息,所以時鐘從不檢查這麼說。
我的問題是這樣的:我怎樣才能讓流發生,並仍然追蹤時間流逝?我是否需要使用本文中描述的多線程? http://www.tutorialspoint.com/python/python_multithreading.htm
我是新來的Python和玩附近的樹莓派硬件樂趣。我已經從Stackoverflow學到了很多東西,謝謝大家:)
我喜歡你的想法,我想我會把它放在我的後面的口袋裏,並嘗試這個多線程的東西。我認爲,如果我可以將流分成單個函數(我認爲它將是main()),並且它可以更新全局變量,然後可以由其他線程訪問,但我可能會很樂意去。 – sakko303