简体   繁体   English

上层导入python

[英]Upper level imports python

I'm using python 3.6 and wondering why I can't import from a package in a parent directory:我正在使用 python 3.6 并想知道为什么我不能从父目录中的包导入:

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.在 example.py 文件夹中,我想导入例如a.pyb.py文件,例如。 import folder_with_code.a . import folder_with_code.a I have tried using .. and sys.path.append but with no joy.我试过使用..sys.path.append但没有任何乐趣。

If your current working directory is project_folder/ then you should be able to import the code from your package like this:如果您当前的工作目录是project_folder/那么您应该能够像这样从包中导入代码:

examples/example_1/example.py示例/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.因此,如果您的工作目录是project_folder/ ,那么您的包(带有__init__.py文件的文件夹)将被 Python 的导入机制识别,在这种情况下,您的导入将是相对于工作目录的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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