首页 > 解决方案 > 使目录成为可导入包的最佳做法是什么?

问题描述

我创建了一些实用函数,都放在一个文件夹中,后来我创建了一些脚本来导入该文件夹中的函数,请参阅以下文件结构,

root
|-- myutils  (folder with util python files)
|   |-- __init__.py  (empty)
|   |-- utils1.py
|   |-- utils2.py  (utils1 is imported by utils2)
|
|-- myscripts
|   |-- hello.py  (try to import utils1 and utils2)

现在的问题是我无法在 hello.py 中导入 utils1/utils2,这是我尝试过的

# This is hello.py

import sys
sys.path.append("root")  # so that we can search root and find myutils

import myutils  # import myutils, this is OK and no errors

x = myutils.utils1.foo()  # ERROR: module 'myutils' has no attribute 'utils1'

我该如何解决这个错误,我的用例的最佳实践是什么?

标签: python

解决方案


推荐阅读