Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 590
Al_P Avatar asked Oct 25 '25 04:10

Al_P


1 Answers

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.

like image 144
Mikko Ohtamaa Avatar answered Oct 26 '25 17:10

Mikko Ohtamaa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!