Discussion:
[Twisted-Python] questions about deferreds and code structure
peter
2015-10-22 08:38:58 UTC
Permalink
hi,


i would like todo a few operations for a bunch of irc servers, basically
all thats done in main for a list of ips.
heres what i came up with (this does not contain the actual class that
inherits from irc.IRCClient code)


questions (i will refer to the pb.codehash.net for line numbers)
1) when not adding printError at the end of the code (line 101) i dont
see error messages for operations in main.
why is that?

printError is also added on line 33 and 36. why wont they produce errors
from main?



2) does this overall structure look like a good idea?
intention: connect to a bunch of servers and do stuff. but not in parrallel.


heres the code nicely formatted
https://pb.codehash.net/760c30b217964139be82930899ba4b49



def printResult(result):
print result


def printError(failure):
print "\tprintError()"
print str(failure)



downloadFinished = False

def startNewDownload(unused):

global downloadFinished

new_data = get_some_bot()

server = new_data["server"]
xdccbot = new_data["xdccbot"]
pack = new_data["pack"]
channel = new_data["channel"]


if not downloadFinished:
point = TCP4ClientEndpoint(reactor, server, 6667)
d = connectProtocol(point, XdccBot())
d.addCallback(main, server, xdccbot, pack, channel)
d.addErrback(printError)

#if this succeeds, or if it fails. do the same: remove old bot
from data and start with the next one
d.addCallback(lambda r: maybeDeferred(remove_bot_from_data,
xdccbot, server, new_data["filename"]))
d.addErrback(printError, "inside main")

d.addCallback(startNewDownload)
d.addErrback(printError)


else:

print "we are done!"
return d






@inlineCallbacks
def main(proto, server, xdccbot, pack, channel):
print "main()"
print "server, bot, pack", server, xdccbot, pack


#this can backfire:
#irc_unknwon: prefix, command, params Helheim.SceneP2P.net
ERR_NOMOTD ['lalala12324', 'MOTD File is missing']
print("Waiting for MOTD...")
yield proto.motdReceived

print("Querying...")
isOnline = yield proto.isOnline(xdccbot)
if isOnline:
print(xdccbot, "is online!")
else:
print(xdccbot, "is *NOT* online!")


joinChannel = yield proto.join_channel(channel)
if joinChannel:
print "we joined some creepy channel"
else:
print "joining didnt work out"



print "sending message"
try:
lala = yield proto.msg_CTCP(xdccbot, pack)
print("lala:", lala)
except lazyBotException as e:
print(e)
#reactor.stop()


#wait for download finish
try:
result = yield proto.downloadFinished
print("result:", result)
except Exception as e:
print("finish:", e)


print("end of code")





d = startNewDownload("lalalal")
d.addCallback(printResult)
d.addErrback(printError)

reactor.run()

Loading...