如何拥有多目录或多包python项目? [英] How to have multi-directory or multi-package python project?

查看:90
本文介绍了如何拥有多目录或多包python项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的项目结构:

package1/__init__.py
package1/file1.py
package1/file2.py

package2/__init__.py
package2/file1.py
package2/file2.py

__init__.py
script1.py
script2.py

不幸的是,我发现我只能从根目录(例如,从script1.py)运行代码.如果我从pakage2/file2.py运行说,文件之间的所有链接都会丢失,即找不到从package2导入的所有package1.

Unfortunately, I found that I can run code only from root directory, for example, from script1.py. If I run say from pakage2/file2.py, all links between files are lost, i.e. all imports of package1 from package2 becomes not found.

Python中正确的目录结构是什么,它约束了所有目录的包结构?

What is the correct directory structure in Python, which constraints package structure over all directories?

推荐答案

您需要将package1package2都放在包中,在这种情况下,它们可以相互导入:

You either need both package1 and package2 to be inside a package, in which case they can both import from each other:

root_package/
    __init__.py
    package1/
    package2/

或将软件包添加到您的PYTHONPATH中,在这种情况下,系统上的任何python脚本都可以从其中导入:

Or add the packages to your PYTHONPATH, in which case any python script on your system can import from them:

export PYTHONPATH="$PYTHONPATH:/path/to/package1:/path/to/package2"

更新:如果您直接运行脚本,则不能将其作为软件包的一部分导入.您应该做的是根据需要在包中定义类和函数,然后从另一个脚本中导入它们:

Update: you cannot import as part of a package if you are running the scripts directly. What you should do is define classes and functions in your packages as desired, then import them from another script:

root_package/
    __init__.py
    my_script.py
    package1/
    package2/

script.py:

from package1 import ...
from package2 import ...

这篇关于如何拥有多目录或多包python项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆