开发者

Import from different directories in python

开发者 https://www.devze.com 2023-02-07 01:07 出处:网络
This is my folder structure: src/ __init__py Lowlevel/ __init__.py ModuleToCheck.Py Test/ __init__.py ModuleToCheck_test.py

This is my folder structure:

src/
  __init__py
  Lowlevel/
    __init__.py
    ModuleToCheck.Py
  Test/
    __init__.py
    ModuleToCheck_test.py

(__init__.py are empty files)

Now I want to import ModuleToCheck.py in ModuleToCheck_test.py

How am I able to do this without appending anything to sys.path?


Update:

from ..Lowlevel import ModuleToCheck leads to:

src$ python Test/ModuleToCheck_test.py 开发者_开发技巧
Traceback (most recent call last):
  File "Test/ModuleToCheck_test.py", line 6, in <module>
    from ..Lowlevel import ModuleToCheck
ValueError: Attempted relative import in non-package


The following is from http://docs.python.org/tutorial/modules.html#intra-package-references

Note that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application should always use absolute imports.

You're running your module ModuleToCheck_test.py as the main module, hence the exception.

One solution is to create a test.py module in your src directory containing the following:

import Test.ModuleToCheck_test

You can then run that module using python test.py

0

精彩评论

暂无评论...
验证码 换一张
取 消