|
| 1 | +#!/usr/bin/env python |
| 2 | +""" |
| 3 | +Use GTK interactively from the prompt, by Brian McErlean and John Finlay |
| 4 | +From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109 |
| 5 | +""" |
| 6 | +import __builtin__ |
| 7 | +import __main__ |
| 8 | +import codeop |
| 9 | +import keyword |
| 10 | +import os |
| 11 | +import re |
| 12 | +import readline |
| 13 | +import threading |
| 14 | +import traceback |
| 15 | +import signal |
| 16 | +import sys |
| 17 | + |
| 18 | +import pygtk |
| 19 | +pygtk.require("2.0") |
| 20 | +import gtk |
| 21 | + |
| 22 | +from matplotlib.cbook import wrap |
| 23 | +from matplotlib.matlab import * |
| 24 | +import matplotlib.matlab |
| 25 | + |
| 26 | +def walk_class (klass): |
| 27 | + list = [] |
| 28 | + for item in dir (klass.__class__): |
| 29 | + if item[0] != "_": |
| 30 | + list.append (item) |
| 31 | + |
| 32 | + for base in klass.__class__.__bases__: |
| 33 | + list = list + walk_class (base()) |
| 34 | + |
| 35 | + return list |
| 36 | + |
| 37 | +class Completer: |
| 38 | + def __init__ (self, lokals): |
| 39 | + self.locals = lokals |
| 40 | + |
| 41 | + self.completions = keyword.kwlist + \ |
| 42 | + __builtin__.__dict__.keys() + \ |
| 43 | + __main__.__dict__.keys() |
| 44 | + def complete (self, text, state): |
| 45 | + if state == 0: |
| 46 | + if "." in text: |
| 47 | + self.matches = self.attr_matches (text) |
| 48 | + else: |
| 49 | + self.matches = self.global_matches (text) |
| 50 | + try: |
| 51 | + return self.matches[state] |
| 52 | + except IndexError: |
| 53 | + return None |
| 54 | + |
| 55 | + def update (self, locs): |
| 56 | + self.locals = locs |
| 57 | + |
| 58 | + for key in self.locals.keys (): |
| 59 | + if not key in self.completions: |
| 60 | + self.completions.append (key) |
| 61 | + |
| 62 | + def global_matches (self, text): |
| 63 | + matches = [] |
| 64 | + n = len (text) |
| 65 | + for word in self.completions: |
| 66 | + if word[:n] == text: |
| 67 | + matches.append (word) |
| 68 | + return matches |
| 69 | + |
| 70 | + def attr_matches (self, text): |
| 71 | + m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text) |
| 72 | + if not m: |
| 73 | + return |
| 74 | + expr, attr = m.group(1, 3) |
| 75 | + |
| 76 | + obj = eval (expr, self.locals) |
| 77 | + if str (obj)[1:4] == "gtk": |
| 78 | + words = walk_class (obj) |
| 79 | + else: |
| 80 | + words = dir(eval(expr, self.locals)) |
| 81 | + |
| 82 | + matches = [] |
| 83 | + n = len(attr) |
| 84 | + for word in words: |
| 85 | + if word[:n] == attr: |
| 86 | + matches.append ("%s.%s" % (expr, word)) |
| 87 | + return matches |
| 88 | + |
| 89 | +class GtkInterpreter (threading.Thread): |
| 90 | + """Run a gtk mainloop() in a separate thread. |
| 91 | + Python commands can be passed to the thread where they will be executed. |
| 92 | + This is implemented by periodically checking for passed code using a |
| 93 | + GTK timeout callback. |
| 94 | + """ |
| 95 | + TIMEOUT = 100 # Millisecond interval between timeouts. |
| 96 | + |
| 97 | + def __init__ (self): |
| 98 | + threading.Thread.__init__ (self) |
| 99 | + self.ready = threading.Condition () |
| 100 | + self.globs = globals () |
| 101 | + self.locs = locals () |
| 102 | + self._kill = 0 |
| 103 | + self.cmd = '' # Current code block |
| 104 | + self.new_cmd = None # Waiting line of code, or None if none waiting |
| 105 | + |
| 106 | + self.completer = Completer (self.locs) |
| 107 | + readline.set_completer (self.completer.complete) |
| 108 | + readline.parse_and_bind ('tab: complete') |
| 109 | + |
| 110 | + def run (self): |
| 111 | + gtk.timeout_add (self.TIMEOUT, self.code_exec) |
| 112 | + try: |
| 113 | + if gtk.gtk_version[0] == 2: |
| 114 | + gtk.threads_init() |
| 115 | + except: |
| 116 | + pass |
| 117 | + |
| 118 | + gtk.mainloop () |
| 119 | + |
| 120 | + def code_exec (self): |
| 121 | + """Execute waiting code. Called every timeout period.""" |
| 122 | + self.ready.acquire () |
| 123 | + if self._kill: gtk.mainquit () |
| 124 | + if self.new_cmd != None: |
| 125 | + self.ready.notify () |
| 126 | + self.cmd = self.cmd + self.new_cmd |
| 127 | + self.new_cmd = None |
| 128 | + try: |
| 129 | + tmp = self.cmd[:-1] |
| 130 | + code = codeop.compile_command (self.cmd[:-1]) |
| 131 | + if code: |
| 132 | + self.cmd = '' |
| 133 | + #print 'Execing', tmp |
| 134 | + exec (code, self.globs, self.locs) |
| 135 | + self.completer.update (self.locs) |
| 136 | + except Exception: |
| 137 | + traceback.print_exc () |
| 138 | + self.cmd = '' |
| 139 | + |
| 140 | + self.ready.release() |
| 141 | + return 1 |
| 142 | + |
| 143 | + def feed (self, code): |
| 144 | + """Feed a line of code to the thread. |
| 145 | + This function will block until the code checked by the GTK thread. |
| 146 | + Return true if executed the code. |
| 147 | + Returns false if deferring execution until complete block available. |
| 148 | + """ |
| 149 | + if (not code) or (code[-1]<>'\n'): code = code +'\n' # raw_input strips newline |
| 150 | + self.completer.update (self.locs) |
| 151 | + self.ready.acquire() |
| 152 | + self.new_cmd = code |
| 153 | + self.ready.wait () # Wait until processed in timeout interval |
| 154 | + self.ready.release () |
| 155 | + |
| 156 | + return not self.cmd |
| 157 | + |
| 158 | + def kill (self): |
| 159 | + """Kill the thread, returning when it has been shut down.""" |
| 160 | + self.ready.acquire() |
| 161 | + self._kill=1 |
| 162 | + self.ready.release() |
| 163 | + self.join() |
| 164 | + |
| 165 | +# Read user input in a loop, and send each line to the interpreter thread. |
| 166 | + |
| 167 | +def signal_handler (*args): |
| 168 | + print "SIGNAL:", args |
| 169 | + sys.exit() |
| 170 | + |
| 171 | +if __name__=="__main__": |
| 172 | + signal.signal (signal.SIGINT, signal_handler) |
| 173 | + signal.signal (signal.SIGSEGV, signal_handler) |
| 174 | + |
| 175 | + prompt = '>> ' |
| 176 | + interpreter = GtkInterpreter () |
| 177 | + interpreter.start () |
| 178 | + interpreter.feed ("from matplotlib import matlab") |
| 179 | + interpreter.feed ("from matplotlib.matlab import *") |
| 180 | + interpreter.feed ("sys.path.append('.')") |
| 181 | + if len (sys.argv) > 1: |
| 182 | + for line in file(sys.argv[1], 'r'): |
| 183 | + print '>>', line.rstrip(), |
| 184 | + interpreter.feed(line) |
| 185 | + gcf().draw() |
| 186 | + print """Welcome to matplotlib. |
| 187 | +
|
| 188 | + help(matlab) -- shows a list of all matlab compatible commands provided |
| 189 | + help(plotting) -- shows a list of plot specific commands |
| 190 | + """ |
| 191 | + |
| 192 | + matplotlib.matlab.interactive = 1 |
| 193 | + |
| 194 | + try: |
| 195 | + while 1: |
| 196 | + command = raw_input (prompt) + '\n' # raw_input strips newlines |
| 197 | + prompt = interpreter.feed (command) and '>> ' or '... ' |
| 198 | + except (EOFError, KeyboardInterrupt): pass |
| 199 | + |
| 200 | + interpreter.kill() |
| 201 | + print |
| 202 | + |
0 commit comments