Skip to content

Python3.x load module path error #133

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
daidai21 opened this issue Jul 21, 2019 · 0 comments
Open

Python3.x load module path error #133

daidai21 opened this issue Jul 21, 2019 · 0 comments
Assignees

Comments

@daidai21
Copy link

Python3.x load module path error

Program execute display like this error: ImportError: No module named 'xxx' also you used like this code: from .xxx import xxx or from ..xxx import xxx.

Example:

  • module/
    • __init__.py
    • A/
      • __init__.py
      • a.py
        def func():
            print("A.a")
    • B/
      • __init__.py
      • b.py
        from ..A.a import func
        
        func()
  • main.py
    from module.B import *

This code will display error when running python3 b.py. I think maybe Python3 Interpreter not support this grammar.
And code will display error when running python3 main.py. if you use sys.paths.append("../") or sys.paths.append("./") like this code, still a mistake. Because program when load module abspath is main.py file, not b.py file. And C++ /C language is not such.

Solve Method

  • __file__ return current file path
  • os.path.abspath(path) return file abspath
  • os.path.dirname() return folder abspath
  • os.path.join() join path

load one level catalog path: os.path.abspath(os.path.join(os.path.dirname(__file__), "../")), load two level catalog path: os.path.abspath(os.path.join(os.path.dirname(__file__), "../../")), etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants