Last active
December 22, 2015 14:49
-
-
Save marceloslacerda/6488503 to your computer and use it in GitHub Desktop.
ipython extension to handle an absent pwd
This file contains 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
"""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, 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
A couple of suggestions:
unload_ipython_extension
will work properly, and I worry that it might actually cause an infinite recursion ifpre_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 leaveunload_ipython_extension
unimplemented: onlyload_ipython_extension
is required.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.errno.ENOENT
in place of a literal2
makes it slightly clearer what the code is doing.