Created
September 7, 2015 17:58
-
-
Save 0x5742/b89b81e02ead9e5cfe57 to your computer and use it in GitHub Desktop.
interactive Python console that runs alongside Gtk
This file contains hidden or 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
| import code | |
| import os | |
| import threading | |
| from gi.repository import Gtk, GLib | |
| class ThreadedConsole(code.InteractiveConsole): | |
| # Set this to True to read $PYTHONSTARTUP. | |
| # This could potentially be a security risk (since it just exec's what | |
| # could potentially be random Python code!), so it's disabled by default, | |
| # but if you have a customized .pythonrc.py, it might be useful to enable. | |
| READ_PYTHONSTARTUP = False | |
| def interact(self, banner=None): | |
| if self.READ_PYTHONSTARTUP: | |
| rc = os.environ.get('PYTHONSTARTUP') | |
| if rc and os.path.isfile(rc): | |
| exec(open(rc).read(), self.locals) | |
| def run(): | |
| super(ThreadedConsole, self).interact(banner) | |
| # If control gets here, the console exited (e.g. Ctrl-D) | |
| Gtk.main_quit() | |
| self.repl_thread = threading.Thread(target=run, daemon=True) | |
| self.repl_thread.start() | |
| def runcode(self, code): | |
| lock = threading.Lock() | |
| lock.acquire() | |
| @GLib.idle_add | |
| def inner(): | |
| # This will run in the GUI thread | |
| try: | |
| super(ThreadedConsole, self).runcode(code) | |
| finally: | |
| # Release the lock that was acquire()'d above, | |
| # so the second acquire() below will stop blocking | |
| lock.release() | |
| # Make this thread wait until inner() is done | |
| lock.acquire() | |
| lock.release() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment