我有一个基本设置如下的 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()
其他.pydef 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()
以下是一些引用资料,以便更好地理解:关于python - 如何在多目录项目中正确导入 python 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65100974/