简体   繁体   中英

Python - import from sibling directory while running as script

I have the following folder structure:

PROJECT_DIR
  | --helpers
  |    |--utils.py
  | --stuff
  |    |--script.py    

I need to run script.py as a script, and from it, I need to use a function from helpers/utils.py.

I tried relative importing from..helpers.utils import func , but it says ImportError: attempted relative import with no known parent package so I added an empty init .py file to each folder, including PROJECT_DIR. Then I read that while running as a script, the python compiler runs the script as if it was the main module, so it doesn't see any other modules outside so relative import cannot be used.

But what should I do if I need to use that function? It's a fairly simple use case, I can't get my head around why it's so hard to import a function from a file outside the current directory. Tho I'm not really interested in the whys, I'd just like to know a solution how people do this.

root_project
└── proj
    ├── __init__.py
    ├── helpers
    │   ├── __init__.py
    │   └── utils.py
    └── stuff
        ├── __init__.py
        └── script.py

With this structure just cd to root_project and use this command:

python -m proj.stuff.script

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