python - 如何在多目录项目中正确导入 python 模块?

标签 python python-3.x modulenotfounderror

我有一个基本设置如下的 python 项目:

imptest.py

utils/something.py
utils/other.py
这是脚本中的内容:
imptest.py
#!./venv/bin/python

import utils.something as something
import utils.other as other

def main():
    """
    Main function.
    """

    something.do_something()
    other.do_other()

if __name__ == "__main__":
    main()
东西.py
#import other

def do_something():
    print("I am doing something")


def main():
    """
    Main function
    """

    do_something()
    #other.do_other()

if __name__ == "__main__":
    main()
其他.py
def do_other():
    print("do other thing!")

def main():
    """
    Main function
    """

    do_other()

if __name__ == "__main__":
    main()
imptest.py 是偶尔为某些事情运行和调用 utils 函数的主文件。
正如你所看到的,我已经在“something.py”中注释掉了一些行,我正在导入“other”模块进行测试。
但是当我想测试something.py 中的某些函数时,我必须运行文件something.py 并取消注释导入行。
这感觉有点笨拙。
如果我离开
import other
取消注释并运行 imptest.py,我收到此错误:
Traceback (most recent call last):
  File "imptest.py", line 5, in <module>
    import utils.something as something
  File "...../projects/imptest/utils/something.py", line 3, in <module>
    import other
ModuleNotFoundError: No module named 'other'
有什么更好的方法来做到这一点?

最佳答案

这里的问题是路径,考虑这个目录结构

main
 - utils/something.py
 - utils/other.py
 imptest.py
当您尝试导入 other使用 something.py 中的相对路径, 那么你会做类似 from . import other .当您执行 $ python something.py 时,这将起作用但是当你运行 $ python imptest.py 时会失败因为在第二种情况下,它会搜索不存在的 main/other.py。
所以为了解决这个问题,我建议你为 something.py 和 other.py 编写单元测试并使用 $ python -m 运行它们。 (mod) 命令。 ( 我强烈推荐这种方法 )
但是....如果您真的不需要太多修改就可以使用现有代码,那么您可以在 中添加这两行东西.py 文件( 这个可行,但我不推荐这种方法 )
import sys, os
sys.path.append(os.getcwd()) # Adding path to this module folder into sys path
import utils.other as other

def do_something():
    print("I am doing something")


def main():
    """
    Main function
    """

    do_something()
    other.do_other()

if __name__ == "__main__":
    main()
以下是一些引用资料,以便更好地理解:
  • Unit testing in python
  • Absolute vs Relative Imports in python
  • 关于python - 如何在多目录项目中正确导入 python 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65100974/

    相关文章:

    python - 基于pandas中的相等性计算数据的拼写长度

    python - 使用 while 循环递增数组中的值,直到所有值 => 100

    python - 在包内找不到子模块

    python - Pandas to_sql() 更新数据库中的唯一值?

    python - 将值列表作为选项传递给 3 个下拉菜单

    python - 从堆叠的 csv 文件中删除空格和标题

    python - flask 运行给我 ModuleNotFoundError

    python - 为 Pandas 数据框创建新列的条件要求

    python - 在多处理循环中捕获异常

    python - 为什么 "from PIL import Image"不起作用,但 "from pil import Image"起作用? (小写 pil)