Run a Twisted reactor inside IPython.
- Copy
twist.py
to~/.ipython/twist.py
- Copy
tpython
to~/bin/tpython
- Make
tpython
executable:chmod +x ~/bin/tpython
You may need to add $HOME/bin
to your path.
#!/bin/sh | |
ipython -i ~/.ipython/twist.py "$@" |
Run a Twisted reactor inside IPython.
twist.py
to ~/.ipython/twist.py
tpython
to ~/bin/tpython
tpython
executable: chmod +x ~/bin/tpython
You may need to add $HOME/bin
to your path.
''' | |
IPython Twisted | |
=============== | |
Run a Twisted reactor inside IPython. Works with newer IPython versions (tested with 0.13.2). | |
Logging is automatically enabled via `logging.basicConfig(level=logging.DEBUG)`. | |
''' | |
import logging | |
logging.basicConfig(level=logging.DEBUG) | |
def __install(): | |
log = logging.getLogger('tpython') | |
log.info('setting up twisted reactor in ipython loop') | |
from twisted.internet import _threadedselect | |
_threadedselect.install() | |
from twisted.internet import reactor | |
from collections import deque | |
from IPython.lib import inputhook | |
from IPython import InteractiveShell | |
q = deque() | |
def reactor_wake(twisted_loop_next, q=q): | |
q.append(twisted_loop_next) | |
def reactor_work(*_args): | |
if q: | |
while len(q): | |
q.popleft()() | |
return 0 | |
def reactor_start(*_args): | |
log.info('starting twisted reactor in ipython') | |
reactor.interleave(reactor_wake) # @UndefinedVariable | |
inputhook.set_inputhook(reactor_work) | |
def reactor_stop(): | |
if reactor.threadpool: # @UndefinedVariable | |
log.info('stopping twisted threads') | |
reactor.threadpool.stop() # @UndefinedVariable | |
log.info('shutting down twisted reactor') | |
reactor._mainLoopShutdown() # @UndefinedVariable | |
ip = InteractiveShell.instance() | |
ask_exit = ip.ask_exit | |
def ipython_exit(): | |
reactor_stop() | |
return ask_exit() | |
ip.ask_exit = ipython_exit | |
reactor_start() | |
return reactor | |
reactor = __install() |