Skip to content

Instantly share code, notes, and snippets.

@minrk
Created February 1, 2014 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minrk/8747974 to your computer and use it in GitHub Desktop.
Save minrk/8747974 to your computer and use it in GitHub Desktop.
# Configuration file for ipython-qtconsole.
# example ipython_qtconsole_config.py for preserving kernel cwd across restarts
# Author: Min RK
# License: Public Domain
from IPython.utils.process import getoutput
from IPython.qt.console.qtconsoleapp import IPythonQtConsoleApp
from IPython.qt.manager import QtKernelManager
class MyQtKernelManager(QtKernelManager):
"""Subclass of QtKernelManager that remembers the cwd across restarts"""
def restart_kernel(self, now=False):
# use lsof to get the cwd of our kernel
lsof = getoutput(["lsof", "-p", "%i" % self.kernel.pid])
for line in lsof.decode('utf8').splitlines():
cmd, pid, user, rest = line.split(None, 3)
# the fifth column (FD) will be 'cwd'
if rest.startswith('cwd'):
# the last column (NAME) is the actual cwd value
cwd = rest.split(None, 5)[-1]
# set the cwd for the next kernel start:
self._launch_args['cwd'] = cwd
super(MyQtKernelManager, self).restart_kernel(now=now)
# tell QtConsoleApp to use our KM class instead of the default
IPythonQtConsoleApp.kernel_manager_class = MyQtKernelManager
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment