How to source or activate a virtual environment within an IPython shell?

I use IPython and the %bookmark magic command but the limitation is that I need to exit the IPython shell to activate a virtual environment and then relaunch IPython.

Is there a way, built into IPython, a third-party package, or a known hack to let me activate the environment without exiting the IPython shell?

Actual workflow

# within ipython shell
exit

# bash shell
cd path/of/my/project
poetry shell  # or pipenv shell
ipython

Intended workflow

%cd -b demographics

# activate venv 

import package # from that env

Solution 1:

This is a good question, but unfortunately, the answer might not be what you are hoping for. If I understood your question correctly - this is not possible. Because virtual shell activation is essentially running child process that setups PATH for another Python interpreter and then PYTHONPATH environment variable for this. A child process can never modify its parent process in any operating system. You cannot, for example, change the Python interpreter you already have running because replacing a running process in-memory is super complicated and never done in practice.

If this is a workflow issue and you definitely want to do this from within IPython, I suggest you write an one-liner copy paste command that would do something along these lines:

  • Launches a new IPython using the virtualenv e.g. (source venv/bin/activate && ipython)
  • Terminates the old, existing IPython session that has been launched from the virtualenv (though not sure how you can exit IPython within IPython prompt)

There is likely a better solution for his workflow question. Maybe there is a workflow that is similar as %%bookmark, but for the whole Python environments and processes, like creating shell scripts.