【问题标题】:Running module from ipython interpreter instead of command line从 ipython 解释器而不是命令行运行模块
【发布时间】:2012-03-09 23:56:39
【问题描述】:

我正在处理一个包,我的结构如下:

 mypackage/
    __init__.py
    __main__.py
    someotherstuff.py
    test/
        __init__.py
        testsomeotherstuff.py

我已对其进行了设置,以便 ma​​in.py 函数运行一些单元测试,并且从命令行执行 python mypackage 可以正常工作。然而,我经常想使用 ipython 首次亮相,但从解释器中,run mypackage 给出了错误ERROR: File 'mypackage.py' not found。我可以通过 run mypackage/__main__.py 手动运行它,但这似乎是错误的。我还应该做些什么来正确设置它吗?

【问题讨论】:

  • 在最近的版本中添加了执行 %run -m mypackage 的功能 - 我不知道这是否适用于您的情况。

标签: python packages ipython


【解决方案1】:

将包作为程序运行是在 Python 2.5 中引入的。我不认为 IPython 有这方面的原生特性,但从 2.7 版开始,Python 标准库就有了,即 runpy.run_module() 函数。请注意,这与 IPython 的 %run 略有不同,因为它将返回模块的全局字典,而不是直接将其导入解释器范围。

【讨论】:

  • 这给了我一个错误:ImportError: mypackage is a package and cannot be directly executed
  • @tdc: 你用的是什么 Python 版本?
  • Python 2.6.5 - 奇怪的是它从命令行运行呢?