简体   繁体   English

如何在开发时调试 python 模块

[英]how to debug python modules while developing

Let's say we are developing a simple python module with the following directory structure假设我们正在开发一个简单的 python 模块,其目录结构如下

.
├── module
│   ├── __init__.py
│   ├── core.py
│   └── helpers.py
└── test.py

contents of init .py init.py的内容

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from .core import print_values

contents of core.py core.py 的内容

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from .helpers import values

def print_values():
    print(values)

if __name__ == '__main__':
    print_values()

contents of helpers.py helpers.py 的内容

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

values = [0, 2, 6]

contents of test.py test.py 的内容

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from module import print_values
print_values()

now if we run python test.py with '.'现在,如果我们运行带有'.' python test.py as the working dir we get the expected output of [0, 2, 6] .作为工作目录,我们得到[0, 2, 6]的预期 output。 Great!伟大的!

So here is the problem, if we change the working dir to './modules' and run python3./core.py the following error will be raised:所以这就是问题所在,如果我们将工作目录更改为'./modules'并运行python3./core.py ,则会引发以下错误:

ImportError: attempted relative import with no known parent package

So the question is how to design modules in a way that we can run python scripts from within it during development?所以问题是如何以我们可以在开发期间从其中运行 python 脚本的方式设计模块?

so the problem appears to be that relative imports coupled with the from keyword tries to import a __init__.py file.所以问题似乎是相对导入加上from关键字试图导入一个__init__.py文件。

In other words, the line换句话说,这条线

from .helpers import values 

tries to read./modules/helpers/ init .py, which does not exist.尝试读取 ./modules/helpers/ init .py,它不存在。 In order to make it work we change the import to:为了使其工作,我们将导入更改为:

if __name__ == '__main__':
    from helpers import values
else:
    from .helpers import values 

Note: since there are a lot of links on google that explain this problem from other use cases (using setup.py as possible solutions for example), i thought it would be a good idea to publish this specific case as i did not encounter it while searching for an answer.注意:由于谷歌上有很多链接可以从其他用例中解释这个问题(例如使用 setup.py 作为可能的解决方案),我认为发布这个特定案例是个好主意,因为我没有遇到它在寻找答案时。

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

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