Skip to content

Instantly share code, notes, and snippets.

@0x5742
Created September 7, 2015 17:58
Show Gist options
  • Select an option

  • Save 0x5742/b89b81e02ead9e5cfe57 to your computer and use it in GitHub Desktop.

Select an option

Save 0x5742/b89b81e02ead9e5cfe57 to your computer and use it in GitHub Desktop.
interactive Python console that runs alongside Gtk
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