从父目录导入 Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19668729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:18:21  来源:igfitidea点击:

Python import from parent directory

python

提问by Justin Carroll

I have the following:

我有以下几点:

         ModuleFolder
              |
              |-->. ModuleFile.py .
              |
              '-->. TestsFolder .
                         |
                         '---> UnitTest1.py

I'm trying to import from the parent directory. In this case I am trying to run "UnitTest1.py" from the test folder, and import from the directory immediately above it (the file "ModuleFile.py").

我正在尝试从父目录导入。在这种情况下,我试图从测试文件夹中运行“UnitTest1.py”,并从其正上方的目录(文件“ModuleFile.py”)导入。

  • I know there are plenty of answers to this already. SO Question1, SO Question2, Every Other SO Question. I just couldn't find "using ../" as a relative import rather than the explicit path.
  • I know that as of Python 2.5 they supported "relative imports" as per the documentation that mentions the use of from .. import *but I am specifically trying to do an import MyModuleNameso I can be more explicit in the unittest and avoid mangling/collisions of names.
  • 我知道这已经有很多答案了。 SO Question1, SO Question2,每隔一个 SO 问题。我只是找不到“使用 ../”作为相对导入而不是显式路径。
  • 我知道从 Python 2.5 开始,他们根据提到使用的文档支持“相对导入”,from .. import *但我特别尝试这样做,import MyModuleName以便我可以在单元测试中更加明确并避免名称的混淆/冲突。

What I am doing (and it is working for me) is the following:

我正在做的(并且对我有用)如下:

sys.path.append("../")

And then importing what I need from the parent directory.

然后从父目录导入我需要的东西。

  • Yes, there is an __init__.py in the parent directory,
  • No, my parent path is not part of the Python path or environment variable
  • Why don't I just add the parent path to the sys.path? Because it's relative. If I am running from /home/workspace/MyModule/unittests/ and my module is under /home/workspace/MyModule/ I assumed adding /home/workspace/MyModule/ to the path won't necessarily be true if a coworker runs this on his machine under his own directory of /home/documents/MyModule.
  • 是的,父目录中有一个 __init__.py,
  • 不,我的父路径不是 Python 路径或环境变量的一部分
  • 为什么我不将父路径添加到sys.path? 因为是相对的。如果我从 /home/workspace/MyModule/unittests/ 运行并且我的模块在 /home/workspace/MyModule/ 我假设添加 /home/workspace/MyModule/ 到路径不一定是真的,如果同事运行这个在他自己的 /home/documents/MyModule 目录下的机器上。

My Question:

我的问题:

Is this Python-proper? If not, what's wrong with this. Is there a better way? Or is this truly an RTFM moment where the answer is in one of the 7+ SO questions I've already looked at? (I saw those all recommending the explicit path rather than the relative path approach I took).

这是 Python 正确的吗?如果没有,这有什么问题。有没有更好的办法?或者这真的是一个 RTFM 时刻,答案就在我已经看过的 7 个以上 SO 问题之一中?(我看到那些都推荐显式路径而不是我采用的相对路径方法)。

Other useful information:

其他有用的信息:

  • Python 2.6
  • Working in Linux but could just as easily jump over to Win.
  • 蟒蛇 2.6
  • 在 Linux 中工作,但也可以轻松跳转到 Win。

采纳答案by Eevee

Don't run the test from the tests folder. Run it from the root of your project, which is the module folder. You should very rarely need to muck with eithersys.pathor PYTHONPATH, and when you do, you're either causing bugs for other libraries down the road or making life harder on your users.

不要从测试文件夹运行测试。从项目的根目录(即模块文件夹)运行它。您应该很少需要使用sys.pathPYTHONPATH,而当您这样做时,您要么会导致其他库的错误,要么使您的用户的生活更加艰难。

python -m TestsFolder.UnitTest1

If you use a test runner like py.test, you can just run py.testfrom the root of your checkout and it'll find the tests for you. (Assuming you name your tests something more like test_unit1.py. Your current naming scheme is a little unorthodox. ;))

如果您使用像py.test这样的测试运行,您可以py.test从结帐的根目录运行,它会为您找到测试。(假设您将测试test_unit1.py命名为更像。您当前的命名方案有点不正统。;))

回答by codeape

My suggestion is:

我的建议是:

Don't try to be clever, do what you're supposed to do. I.e. make sure that your modules and packages are somewhere in your Python path.

不要试图变得聪明,做你应该做的。即确保你的模块和包在你的 Python 路径中的某个地方。

The simplest way is to set the environment variable PYTHONPATH in the shell that you use to execute your scripts:

最简单的方法是在用于执行脚本的 shell 中设置环境变量 PYTHONPATH:

$ export PYTHONPATH=/the/directory/where/your/modules/and/packages/are
$ cd /the/directory/where/your/unit/tests/are
$ python test1.py

回答by Laurent LAPORTE

It's better to insert your relative path at the begening of sys.pathlike this:

最好在开始时插入您的相对路径,sys.path如下所示:

import sys
sys.path.insert(0, '../')

回答by Shubham Chaudhary

Make your test folder a module (by adding __init__.py).
Then you can use run python -m tests.test_nameor use the following Makefilein your project home:

使您的测试文件夹成为模块(通过添加__init__.py)。
然后你可以在你的项目主页中使用 runpython -m tests.test_name或使用以下Makefile

TEST_FILES = $(wildcard tests/test_*.py)
TESTS = $(subst .py,,$(subst /,.,$(TEST_FILES)))
all.PHONY: test
test:
    @- $(foreach TEST,$(TESTS), \
        echo === Running test: $(TEST); \
        python -m $(TEST); \
        )

回答by PalFS

You can also make symlink of the module path which you want to import and then use that symlink to import. Create a symlink in the python dist-packages.

您还可以创建要导入的模块路径的符号链接,然后使用该符号链接进行导入。在 python dist-packages 中创建一个符号链接。

To create a symlink:

创建符号链接:

ln -s "/path/to/ModuleFolder" "/path/to/python/dist/packages/module_symlink_name"

ln -s "/path/to/ModuleFolder" "/path/to/python/dist/packages/module_symlink_name"

To import module in the script:

在脚本中导入模块:

from module_symlink_name import ModuleFile

No need to export python path or modifying sys path.

无需导出python路径或修改sys路径。