[英]Organize Python package to run from its top-level directory?
How do I organize a Python package so its code runs from the top-level directory without adding that directory to the host's Python path? 如何组织Python程序包,以便其代码从顶级目录运行而又不将该目录添加到主机的Python路径?
I would also like to organize the code so I can run tests from the various test subdirectories, again without adding the package's top-level directory to the python path. 我还希望组织代码,以便可以从各个测试子目录运行测试,而无需再次将程序包的顶级目录添加到python路径。
Consider the following code layout: 考虑以下代码布局:
foobar/
__init__.py
README.txt
its_a_module.py
one_package/
__init__.py
foo.py
bar.py
tests/
__init__.py
testing_one_package.py
tests/
__init__.py
test_foobar.py
How do I organize the import statements of my various modules, and the contents of my init .py files, to meet those objectives? 如何组织各个模块的导入语句以及init .py文件的内容,以满足这些目标?
(I would like to use distutils to manage the code, and I read that running the code from the top-level directory is a useful precursor.) (我想使用distutils来管理代码,并且我读到从顶级目录运行代码是有用的先驱。)
You can add ..
to your PYTHONPATH
. 您可以将..
添加到您的PYTHONPATH
。 That will satisfy your first two conditions: 这将满足您的前两个条件:
You can always import absolutely, import foobar
and from foobar.one_package import ...
no import one_package
and other relative imports. 您始终可以绝对import foobar
, from foobar.one_package import ...
import foobar
from foobar.one_package import ...
不import one_package
和其他相对导入。 In this way you can run any submodule from the foobar dir. 这样,您可以从foobar目录中运行任何子模块。
For the other two stipulations, 对于其他两个规定,
you could add grandparents and great-grandparents of the PWD
to the PYTHONPATH
but I have never heard of this and it sounds bad. 您可以在PYTHONPATH
添加PWD
祖父母和曾祖父母,但我从未听说过,这听起来很糟糕。 You can't really get around installing foobar
, ie, putting it on your path, if you want the foobar package to be available no matter how deeply you go. 如果您想使foobar软件包无论您走到多远都可以使用,则无法真正解决安装foobar
,即将其放置在路径上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.