如何通过运行 'python ...' 从 shell 启动 ipython?

33 投票
6 回答
36706 浏览
提问于 2025-04-17 08:18

我想在一个Python启动代码中添加一些命令行选项,以便真正启动一个ipython的命令行界面。我该怎么做呢?

6 个回答

5

也许一个选择就是像这样把 ipython 嵌入到你的代码里

def some_function():
    some code

    import IPython
    IPython.embed()

当你在某段代码中运行这个函数时,它会启动一个 ipython 终端,这个终端的作用范围就是从哪里调用这个函数的地方。

14

你可以先为你的特定版本安装 IPython,然后通过模块名称来启动 Python,比如:

$ 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]:

这样你甚至可以安装多个 Python 版本,并为每个版本单独启动一个 IPython 解释器。为了方便,你可以在 .bashrc 文件中设置一个别名,比如:

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

这样你就可以轻松地为特定版本启动 IPython 了:

$ 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]:

你还可以查看 https://github.com/ipython/ipython#development-and-instant-running 了解更多信息。

编辑 关于 Python3.12:我在用这种方式安装 Python3.12(来自 deadsnakes)下的 IPython 时遇到了一些问题。根本原因是 pkgutil 不认识 ImpImporter,因为它已经被弃用了,这意味着我在 Python3.12 下的 pip 安装出现了问题。感谢 ensurepip,解决方法很简单:python3.12 -m ensurepip --upgrade。然后 python3.12 -m pip install IPython 就可以正常工作了。

76

要直接在Python中启动IPython命令行,可以使用以下代码:

from IPython import embed

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

embed()

或者,你也可以直接在命令行中运行它:

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

embed这个命令会在命令行中使用所有你当前的本地变量。

如果你想提供一些自定义的本地变量(也就是在命令行中可以用到的变量),可以看看 IPython.terminal.embed.InteractiveShellEmbed 这个内容。

撰写回答