问题
I have the codes for twython streaming and it is working.
def read_cred(file): in_handle = open(file,'r')
cred = {}
for ln in in_handle:
data = ln.strip('\r\n').split('=')
if len(data) > 1:
key = data[0].strip(' ').lower()
value = data[1].strip(' ')
cred[key] = value
else:
print "error in parsing credentials file"
return cred
cred = read_cred(sys.argv[1])
class MyStreamer(TwythonStreamer): def on_success(self, data): act(data)
def on_error(self, status_code, data):
print status_code, data
stream = MyStreamer(cred['consumer_key'], cred['consumer_secret'], cred['access_token_key'], cred['access_token_secret'])
keywords = sys.argv[2]
stream.statuses.filter(track=keywords)
However, I want to create a UI in django framework which consist of a 'start' and a 'stop' button. What should I do to stop the twython streaming when I clicked on the button 'stop' ? Can give me some simple examples pls?
回答1:
As long as the stop button is bound to the rest of the app (I haven't used Django, so I can't provide a simple example) then calling sys.exit() should do the job.
Django might have some other method for terminating a process built into it or some specific examples in its documentation. You should check that to confirm this answer.
回答2:
You can use the disconnect() function as described in the documentation of Twython - https://twython.readthedocs.org/en/latest/api.html#twython.TwythonStreamer.disconnect
def on_stop(self, status_code, data):
self.disconnect()
def on_start(keywords):
stream = MyStreamer(cred['consumer_key'], cred['consumer_secret'],
cred['access_token_key'], cred['access_token_secret'])
stream.statuses.filter(track=keywords)
来源:https://stackoverflow.com/questions/18862534/is-it-possible-to-stop-twython-streaming-at-certain-point-of-time