简体   繁体   中英

How to Fix Path Resolution for Imports

I am having an issue importing packages into a project when I merged my portion into a pull request with a larger project. runner.py utilizes modules and scripts within each of the sub-directories in Dir 2. Some of those modules in the sub directories now need to access modules in Dir 1 and Dir 3.

I have tried appending the system path, which is not the correct way to do this, but that seems to work for some things asnd break others. I've tried specifying the parent directory and that doesn't seem to work because Python changes the working directory on the call. So if I start in Project Directory and do python Dir_2/runner.py my actual working directory would be Project Directory/Dir_2 and not Project Directory. If I sys.path.append(os.getcwd()) I break in some of the standard library imports. What am I missing here?

Things I've Tried

  • Use relative referencing by appending . or .. to the front of the imports. This Generates

    __main__module does not exist or "You are attempting to access a directory above the root of this project".

Shape of the project

  • Project Directory
    • Dir 1
    • Dir 2
      • runner.py
      • SubDir 1
      • SubDir 2
      • SubDir 3
    • Dir 3

Don't run files in subdirectories as though they were scripts. If it's part of a package structure, it's a module , not a script, so run it as one:

python -m dir2.runner

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM