-
-
Save fccoelho/2874403 to your computer and use it in GitHub Desktop.
Prototype of an extension to provide acess to virtual python environment on an IPython notebook cell
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
import sys | |
import os | |
import shlex | |
from subprocess import Popen, PIPE | |
from IPython.utils.py3compat import unicode_to_str | |
def workon(line, cell): | |
if not os.path.exists(os.environ['WORKON_HOME']+line): | |
print >> sys.stderr, "Environment {} does no exist.".format(line) | |
return | |
env_activate_cmd = 'bash -c source '+os.environ['WORKON_HOME'] + '/{}/bin/activate'.format(line) | |
cmd = shlex.split(env_activate_cmd) + ["&&","python","-"] | |
p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE, shell=True) | |
out,err = p.communicate(cell) | |
if err: | |
print >> sys.stderr, err | |
print out | |
if 'WORKON_HOME' in os.environ: | |
get_ipython().register_magic_function(workon, 'cell') | |
""" | |
From now, you can do: | |
%%workon pre_existing_env | |
# Now the following python code will be executed under pre_existing_env | |
import sys | |
print sys.version | |
""" |
Rather than calling get_ipython()
or InteractiveShell()
, an IPython extension should offer a load_ipython_extension(ip)
method, which will be called with the shell object when it's loaded. Docs: http://ipython.org/ipython-doc/stable/config/extensions/index.html
(The rationale for this is that we have a long term goal to allow more than one InteractiveShell object in the same process - so we're trying not to treat it like a singleton)
I'll study other extensions and modify my code to conform.
thanks @takluyver
Thanks @turicas for the tip on how to make the bash command work...
@fccoelho, PEP8, please! :-)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@minrk : Would this be a start of a virtualenv cell?
it requires virtualenv to be installed and the env to exist prior to using this