11.3.3.3.3. Main runner¶
I fit all this into one executable. However, I quickly discovered that both CherryPy web apps and irclib bots like to run in the main thread. This means I need to launch two python shells, one running the web app, the other running the ircbot, and I need the web app to be able to talk to the irc bot. This is a piece of cake with Spring Python. All I need to utilize is a remoting technology:
if __name__ == "__main__":
# Parse some launching options.
parser = OptionParser(usage="usage: %prog [-h|--help] [options]")
parser.add_option("-w", "--web", action="store_true", dest="web", default=False, help="Run the web server object.")
parser.add_option("-i", "--irc", action="store_true", dest="irc", default=False, help="Run the IRC-bot object.")
parser.add_option("-d", "--debug", action="store_true", dest="debug", default=False, help="Turn up logging level to DEBUG.")
(options, args) = parser.parse_args()
if options.web and options.irc:
print "You cannot run both the web server and the IRC-bot at the same time."
sys.exit(2)
if not options.web and not options.irc:
print "You must specify one of the objects to run."
sys.exit(2)
if options.debug:
logger = logging.getLogger("springpython")
loggingLevel = logging.DEBUG
logger.setLevel(loggingLevel)
ch = logging.StreamHandler()
ch.setLevel(loggingLevel)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)
if options.web:
# This runs the web application context of the application. It allows a nice web-enabled view into
# the channel and the bot that supports it.
applicationContext = ApplicationContext(CoilyWebClient())
# Configure cherrypy programmatically.
conf = {"/": {"tools.staticdir.root": os.getcwd()},
"/images": {"tools.staticdir.on": True,
"tools.staticdir.dir": "images"},
"/html": {"tools.staticdir.on": True,
"tools.staticdir.dir": "html"},
"/styles": {"tools.staticdir.on": True,
"tools.staticdir.dir": "css"}
}
cherrypy.config.update({'server.socket_port': 9001})
cherrypy.tree.mount(applicationContext.get_object(name = "root"), '/', config=conf)
cherrypy.engine.start()
cherrypy.engine.block()
if options.irc:
# This runs the IRC bot that connects to a channel and then responds to various events.
applicationContext = ApplicationContext(CoilyIRCServer())
coily = applicationContext.get_object("bot")
coily.service.start()