我在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!")
runner.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也很高兴,但我不能运行我的测试。
答案 0 :(得分:1)
尝试使用-m选项运行代码:
python -m tests.runner
为什么在PEP 338中解释:
Python 2.4添加命令行开关-m以允许模块 使用Python模块命名空间定位以作为脚本执行。
以及此处的一些答案:What is the -m switch for in Python?