Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I launch ipython from shell, by running 'python ...'?

I would like to add some commandline options to a python launch code in order to actually invoke an ipython shell. How do I do that?

like image 516
Shwouchk Avatar asked Aug 31 '25 15:08

Shwouchk


2 Answers

To start IPython shell directly in Python:

from IPython import embed

a = "I will be accessible in IPython shell!"

embed()

Or, to simply run it from command line:

$ python -c "from IPython import embed; embed()"

embed will use all local variables inside shell.

If you want to provide custom locals (variables accessible in shell) take a look at IPython.terminal.embed.InteractiveShellEmbed

like image 139
rgtk Avatar answered Sep 02 '25 06:09

rgtk


You can first install IPython for your specific version and then start Python with module name, e.g.:

$ python3.7 -m pip install IPython
$ python3.7 -m IPython

Python 3.7.7 (default, Mar 10 2020, 17:25:08) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]:

So you can even have multiple Python versions installed and start an IPython interpreter for each version separately. A next step for convenience would be to alias the command, e.g. in .bashrc:

alias ipython3.7='python3.7 -m IPython'

Then you can easily start IPython for the specific version(s):

$ ipython3.7
 
Python 3.7.7 (default, Mar 10 2020, 17:25:08) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]:

See also https://github.com/ipython/ipython#development-and-instant-running.

EDIT for Python3.12: I had some issues, getting IPython installed under Python3.12 (from deadsnakes) this way. The underlying problem was that pkgutil does not know ImpImporter, which is deprecated, meaning that I had a broken pip installation for Python3.12. Thanks to ensurepip, the solution is simple: python3.12 -m ensurepip --upgrade. Then python3.12 -m pip install IPython should work.

like image 34
colidyre Avatar answered Sep 02 '25 08:09

colidyre