Python:导入模块麻烦,取决于运行模式

标签 python import

我正在 virtualenv 中设置一个项目:

py-procr/
  procr/
    bin/
    lib/
    include/
    core/
      pcp.py
      __init__.py
  tests/
    __init__.py
    runner.py

pcp.py:

#!/usr/bin/env python

def hello(msg = "Hello, World!"):
    print(msg)

def zero_pad(i,  n):
    return "%0{n}d"

if __name__ == '__main__':
    hello("Main!")

运行者.py:

import unittest
from procr.core.pcp import *

class TestHelpers(unittest.TestCase):

    def setUp(self):
        self.alfa = "alfa"

    def test_zero_pad(self):
        padded_i = zero_pad(3,  5)
        self.assertEqual(padded_i,  "%0{n}d")

if __name__ == '__main__':
    unittest.main()

这是运行模式:

(procr)a@s ~/spaces/python/py-procr $ python procr/core/pcp.py 
Main!
(procr)a@s ~/spaces/python/py-procr $ python tests/runner.py 
Traceback (most recent call last):
  File "tests/runner.py", line 2, in <module>
    from procr.core.pcp import *
ImportError: No module named 'procr'   ;; also 'core' and 'pcp' if you cut the import statement
(procr)a@s ~/spaces/python/py-procr $ python
Python 3.4.2 (default, Oct  8 2014, 13:44:52) 
[GCC 4.9.1 20140903 (prerelease)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import procr.core.pcp
>>> import tests.runner   ;; runner.py: from procr.core.pcp import *
>>> import tests.runner   ;; runner.py: from core.pcp import *
>>> import tests.runner   ;; runner.py: from pcp import *
>>> import core.pcp
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'core'

我的Python路径:

>>> sys.path
['', '/home/alexey/spaces/python/py-procr/procr/lib/python34.zip', '/home/alexey/spaces/python/py-procr/procr/lib/python3.4', '/home/alexey/spaces/python/py-procr/procr/lib/python3.4/plat-linux', '/home/alexey/spaces/python/py-procr/procr/lib/python3.4/lib-dynload', '/usr/lib64/python3.4', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-linux', '/home/alexey/spaces/python/py-procr/procr/lib/python3.4/site-packages']
>>>

所以 IDE/编译器 (Eric) 很高兴; python REPL 也很高兴,但我无法运行我的测试。

最佳答案

尝试使用 -m 选项运行代码:

python -m tests.runner

PEP 338 中解释了原因:

Python 2.4 adds the command line switch -m to allow modules to be located using the Python module namespace for execution as scripts.

这里还有一些答案:What is the -m switch for in Python?

关于Python:导入模块麻烦,取决于运行模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27341525/

相关文章:

python - 向 Django 管理添加自定义字段

python - 多次调用 savefig() 导致 Spyder IDE/IPython 内核死机崩溃

python - QGtkStyle 无法解析 GTK

jupyter中的Python Import cv2错误适用于mac终端

python - 从 Python 中的子文件夹导入

mysql - 将 .sql 文件的文件夹导入单个数据库

mysql - 加载 XML 本地内嵌文件

Python、fastAPI、uvicorn - 加载 ASGI 应用程序时出错。无法导入模块 "main"

python - 如何向 CountVectorizer 添加权重因子

python - Python 3.5 中的包导入失败