【问题标题】:Import Python file within a different parent directory在不同的父目录中导入 Python 文件
【发布时间】:2018-02-07 13:29:36
【问题描述】:

我的目录结构如下:

- src
    - __init__.py
    - scripts
        - __init__.py
        - preprocessing.py
    - project1
        - main.py
    - project2
        - main.py

我正在尝试从 main.py 两个文件中访问 scripts 文件夹中的脚本。

我尝试添加__init__.py(空白)文件,并使用import scriptsfrom src import scriptsfrom .. import scripts 导入。这些似乎都不起作用。

我要么得到:ValueError: Attempted relative import in non-package,要么找不到模块。

提前致谢!


附:我假设目录结构很快就会变得更深(例如scriptsproject1 / project2 中的多个子目录)。因此,如果这些也是处理此问题的简单方法,那将非常感激。

【问题讨论】:

  • 似乎与此问题重复 stackoverflow.com/questions/4383571/…
  • 您使用的是什么版本的 Python?你的sys.path中是否包含src的目录?
  • 我使用的是 2.7.10。我尝试将它添加到我的sys.path,但并没有真正改变。另外,我听说使用__init__.py 意味着您不必更改sys.path,因为它可以作为包导入。

标签: python import directory parent subdirectory


【解决方案1】:

解决这个问题的一种方法(尽管不是最干净的方法)是将根目录手动添加到 sys.path 变量中,以便 python 可以在其中查找模块,例如,您可以在 main.py 中添加这些行在顶部:

#/src/project1/main.py
import os
import sys
sys.path.append(os.getcwd() + '\\..\\')  # this is the src directory

这将允许python在运行脚本的目录中查找模块,这将起作用:

import scripts.preprocessing

请记住,python 只会在脚本运行时在同一目录或以下目录中查找模块。如果你启动/src/project2/main.py,python对/src/project1/或/src/scripts/一无所知

【讨论】:

  • 感谢您的回复。我试图避免将此添加到每个想要访问 scripts 的文件中
  • 您也可以将这些行添加到目录的 init.py 中,然后该目录中的所有 python 文件都应该可以访问脚本。
  • 您能否在init.py 中提供这些行之一的示例?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-11
  • 2013-07-17
  • 2012-04-22
  • 2023-02-02
  • 1970-01-01
  • 2018-10-09
  • 1970-01-01
相关资源
最近更新 更多