【问题标题】:Import python files from other directory without sys.path.append or changing PATH从其他目录导入 python 文件,无需 sys.path.append 或更改 PATH
【发布时间】:2015-11-20 14:27:06
【问题描述】:

我有以下文件夹结构

project
  +folder src
    +file main.py
    +file __init__.py
  +folder tests
    +file test.py
    +file __init__.py
  +file __init__.py

所有__init__ 文件都是空的。

现在我希望能够在任何地方运行test.py,这很重要。

test.py 来电

import src

因为它需要来自main.py 的函数。 这会导致错误:

ImportError: no module named src

我找到的解决方案包括将 sys.path.append 命令添加到 test.py 或将文件夹 src 添加到我的 PATH 环境变量 - 没有其他方法吗?

我不能强制每个用户更改他们的PATH,也不能将sys.path.append 命令添加到所有测试文件中。

【问题讨论】:

  • 你能取消在任何地方运行的要求吗?您可以要求 test.py 存储在您的项目目录中,并在运行时提示输入目标目录。你会先导入 src 然后调用 os.chdir('/run/script/here/')

标签: python import module path sys.path


【解决方案1】:

您可以创建应用程序包并将其安装在运行测试的环境中。教程见这里http://python-packaging.readthedocs.org/en/latest/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-31
    • 2017-01-25
    • 2021-01-31
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 2019-09-14
    相关资源
    最近更新 更多