简体   繁体   English

在Python中从父目录导入不起作用

[英]Importing from a parent directory in Python does not work

Even with an __init__.py in the parent directory. 即使在父目录中使用__init__.py

parentDir\
    __init__.py
    targetDir\
        __init__.py
        something.py
    thisDir\
        main.py

In main.py: 在main.py中:

import .targetDir.something

This does not work. 这是行不通的。 I tried: 我试过了:

from . import targetDir
from targetDir import something

This doesn't work, either. 这也不起作用。 Are there any Pythonic solutions for doing something as simple as importing a module from a directory in the parent directory? 是否有任何Pythonic解决方案可完成从父目录中的目录导入模块一样简单的操作?

I believe you'd need __init__.py in thisDir and then you need to go up a level in the package hierarchy: 我相信您需要在thisDir __init__.py ,然后需要在软件包层次结构中上thisDir

from ..  import targetDir

or: 要么:

from ..targetDir import something

May be this is not a cleanest solution, but you can do something like this: 可能这不是最干净的解决方案,但是您可以执行以下操作:

import sys
import os

topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
                                       os.pardir, os.pardir))
if os.path.exists(os.path.join(topdir, "targetDir", "__init__.py")):
    sys.path.insert(0, topdir)

from targetDir import something

Example: 例:

mkdir -p parentDir/targetDir
mkdir -p parentDir/thisDir
touch parentDir/__init__.py
touch parentDir/targetDir/__init__.py
echo "print 'Im here'" > parentDir/targetDir/something.py

then place the code in parentDir/thisDir/main.py and it should print Im here 然后将代码放在parentDir/thisDir/main.pyIm here打印Im here

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

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