How to import the src from the tests module in python
我有一个应用程序,我想使用
1 2 3 4 5 6 7 8 9 10 | root_dir ├── src │ ├── cmds │ │ ├── baz.py │ │ ├── __init__.py │ │ └── bar.py │ └── foo.py └── tests ├── cmds.py └── __init__.py |
我想测试来自
但在
我怎样才能做到这一点?
基本上,我想用
我试着把
编辑:我的进口和进口声明是:
1 2 3 | import sys sys.path.append('../src') from cmds.baz import about |
追溯到:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | Traceback (most recent call last): File"/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File"/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File"/usr/lib/python2.7/unittest/__main__.py", line 12, in <module> main(module=None) File"/usr/lib/python2.7/unittest/main.py", line 94, in __init__ self.parseArgs(argv) File"/usr/lib/python2.7/unittest/main.py", line 149, in parseArgs self.createTests() File"/usr/lib/python2.7/unittest/main.py", line 158, in createTests self.module) File"/usr/lib/python2.7/unittest/loader.py", line 128, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File"/usr/lib/python2.7/unittest/loader.py", line 100, in loadTestsFromName parent, obj = obj, getattr(obj, part) AttributeError: 'module' object has no attribute 'cmds' |
要做的一件非常错误的事情是向
1 2 3 4 5 6 | # assuming that the code is in test's __init__.py import os import sys sys.path.insert(0, os.path.abspath( os.path.join(os.path.dirname(__file__), '../src/') )) # now you can be sure that the project_root_dir/src comes first in sys.path |
我想你差不多明白了。但是当您从根目录运行测试时,我想您的路径(
1 2 3 4 5 6 7 | import os import sys ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..') sys.path.append(os.path.join(ROOT, 'src')) from cmds.baz import about |