繁体   English   中英

从其他目录导入python文件,而无需sys.path.append或更改PATH

[英]Import python files from other directory without sys.path.append or changing PATH

我有以下文件夹结构

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

所有__init__文件均为空。

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

test.py电话

import src

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

ImportError: no module named src

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

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

您可以创建应用程序包,然后将其安装在运行测试的环境中。 请参阅此处以获得教程http://python-packaging.readthedocs.org/en/latest/

暂无
暂无

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

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