【问题标题】:Issue with IPythonIPython 的问题
【发布时间】:2017-06-30 18:28:51
【问题描述】:

python_test.py 文件中,我插入了:

def my_contains(elem, lst):
    return elem in lst
def my_first(lst):
    return lst[0]

import IPython
IPython.embed()

执行python3 python_test.py后,我得到了:

Traceback (most recent call last):
  File "python_test.py", line 6, in <module>
    import IPython
ImportError: No module named 'IPython'

事实上,我希望在执行我的代码之后,shell 是否可以保持打开状态,以便我可以测试该代码。此时有人可以帮助我吗?

【问题讨论】:

  • 你可能需要用pip install ipython安装它。
  • @WillemVanOnsem 安装IPython后好像还是不行。
  • 这是python 3,还是python 2。也许你需要改用pip3
  • @WillemVanOnsem 谢谢,它有效!

标签: python ipython embed


【解决方案1】:

来自手册页:

-i 当脚本作为第一个参数传递或使用 -c 选项时,在执行脚本或命令后进入交互模式。它不读取 $PYTHONSTARTUP 文件。这对于在脚本引发异常时检查全局变量或堆栈跟踪很有用。

我对您的代码进行了如下测试,它对我有用:

python3 -i python_test.py
>>> my_first([3, 2, 1])
3
>>> my_contains(2, [1, 10, 100])
False
>>> my_contains(1, [2, 1, 3])
True

这个答案几乎是从https://stackoverflow.com/a/5280210/7554621逐字复制的

对于IPython,它似乎找不到模块,这意味着它没有安装,安装不正确,不知道在哪里找到它,名称不正确,或者使用不正确。我考虑在这里安装它http://ipython.readthedocs.io/en/stable/install/index.html

安装之后,我只是简单的用ipython代替了python3来加载文件,进入交互式shell:

@WillemVanOnsem 在上面的 cmets 中提出了一个很好的观点,即可能需要使用 pip3 而不是 pip。对我来说,pip 工作正常并且安装正确。

pip install ipython
ipython -i python_test.py
Python 3.5.1 (default, Apr 18 2016, 11:46:32)

In [1]: my_contains(1, [1, 2, 3])
Out[1]: True

In [2]: my_first([1, 2, 3])
Out[2]: 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多