Skip to content

Instantly share code, notes, and snippets.

@marceloslacerda
Last active December 22, 2015 14:49
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 marceloslacerda/6488503 to your computer and use it in GitHub Desktop.
Save marceloslacerda/6488503 to your computer and use it in GitHub Desktop.
ipython extension to handle an absent pwd
"""Once this extension is installed to a ipython instance, it no longer crashes if the current directory is removed.
Based on the work of dhananjaysathe
More info at: https://github.com/ipython/ipython/pull/811"""
import os, logging, IPython, errno
def getcwdu(self):
"""Graciously handles cases when PWD does not exist.
Defaults to home directory eliminating the OSError exception.
"""
try:
current_dir_path = os.getcwdu()
except OSError as e :
if e.errno == errno.ENOENT:
logging.warn("Path does not exist, defaulting to Home Directory")
os.chdir(os.path.expanduser('~'))
def load_ipython_extension(ip):
ip.set_hook('pre_run_code_hook', getcwdu)
@takluyver
Copy link

A couple of suggestions:

  • I'm not sure that your unload_ipython_extension will work properly, and I worry that it might actually cause an infinite recursion if pre_run_code_hook tries to call itself. I'm not sure if we have a way to unregister a hook function. If not, you can leave unload_ipython_extension unimplemented: only load_ipython_extension is required.
  • Does the HOME environment variable exist in all cases, including on Windows? If not, os.path.expanduser('~') may be a safer option.
  • except OSError as e will make it work on Python 3 as well.
  • Using errno.ENOENT in place of a literal 2 makes it slightly clearer what the code is doing.

@marceloslacerda
Copy link
Author

@takluyver, I was unable to reproduce the infinite recursion when unloading cd_ipy. However, since I was unable to unload the extension at all(%unload cd_ipy didn't produce any effect) and didn't find anything related to unregistering a hook, I thought it was safe enough to simply remove the unload function as you suggested.

I did follow your other suggestions and I'm thankful for you advices(I'll use the syntax for exception catching in my future projects). I only hoped, though, that you would point out a ipython-ish way to raise a warning, the error message that my extension produce contrasts with colorful error messages of ipython :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment