Created
May 8, 2013 22:18
-
-
Save minrk/5544117 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Simple IPython namespace watcher | |
watches a variable in an IPython kernel's namespace, | |
and displays it any time it changes. | |
Requires IPython 1.0-dev | |
Usage: | |
python watcher.py [variable_name] [connection-file-pattern] | |
""" | |
import sys | |
import pprint | |
from IPython.kernel.blocking import BlockingKernelClient | |
from IPython.kernel import find_connection_file | |
block = """ | |
ip = get_ipython() | |
from IPython.display import display | |
from IPython.utils import io | |
parent = ip.display_pub.parent_header | |
def display_the_frame(): | |
if "{0}" not in ip.user_ns: | |
return | |
# detach display from triggering cell, | |
# so they don't see our extra output | |
ip.display_pub.set_parent(parent) | |
display(ip.user_ns['{0}'], metadata={{'watcher': True}}) | |
ip.register_post_execute(display_the_frame) | |
""" | |
def watcher(cf, key): | |
kc = BlockingKernelClient(connection_file=cf) | |
kc.load_connection_file() | |
kc.start_channels() | |
kc.execute(block.format(key)) | |
reply = kc.get_shell_msg() | |
if reply['content']['status'] != 'ok': | |
print("Watcher setup failed:") | |
print('\n'.join(reply['content']['traceback'])) | |
return | |
previous = '' | |
while True: | |
msg = kc.get_iopub_msg() | |
if msg['msg_type'] != 'display_data': | |
continue | |
content = msg['content'] | |
if not content['metadata'].get('watcher'): | |
# not the result of our watch display | |
continue | |
todisplay = content['data'].get('text/plain', '') | |
if todisplay == previous: | |
# no change | |
continue | |
print('-' * 30) | |
print(todisplay) | |
previous = todisplay | |
if __name__ == '__main__': | |
if len(sys.argv) > 1: | |
key = sys.argv[1] | |
else: | |
key = raw_input("key to watch: ") | |
if len(sys.argv) > 2: | |
pattern = sys.argv[2] | |
else: | |
pattern = '*' | |
cf = find_connection_file(pattern) | |
print("loading connection file: %r" % cf) | |
print("watching key: %r" % key) | |
watcher(cf, key) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment