简体   繁体   中英

Upper level imports python

I'm using python 3.6 and wondering why I can't import from a package in a parent directory:

project_folder/
   folder_with_code/
         __init__.py
         a.py
         b.py
   examples/ 
         example_1/
             example.py
   tests/
         some_test.py
   execute_tests.py

In the example.py folder I want to import for example the a.py or b.py files, eg. import folder_with_code.a . I have tried using .. and sys.path.append but with no joy.

If your current working directory is project_folder/ then you should be able to import the code from your package like this:

examples/example_1/example.py

import folder_with_code.a

So if your working directory is project_folder/ , then your packages (folders with __init__.py files) will be recognized by the import mechanism of Python, and in that case your imports will be relative from working directory.

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