[英]What import system should I use when I want to run my application both 'from source' and from installing with setuptools?
Consider this application: 考虑以下应用程序:
.
├── LICENSE
├── MANIFEST.in
├── program
│ ├── apple.py
│ ├── __init__.py
│ ├── __main__.py
│ ├── nonfruit.py
│ ├── pear.py
│ ├── strawberry.py
│ └── vegetables
│ ├── carrot.py
│ ├── __init__.py
│ └── lettuce.py
├── README.md
├── setup.cfg
└── setup.py
__main__.py
is the file that users should run to use my program. __main__.py
是用户应运行以使用我的程序的文件。 I am distributing my program via PyPI and so I want to be able to install it via pip as well. 我正在通过PyPI分发程序,因此我也希望能够通过pip进行安装。 Because of that, I created a
setup.py
file with an entry point: 因此,我创建了一个带有入口点的
setup.py
文件:
entry_points = {
'console_scripts': ['pg=program.__main__:main']}
The problem I'm facing is that there are several imports in my program, and these result in the situation that my program does run 'locally' (by executing python ./__main__.py
, but not from installation (by running pg
). Or, depending on the way I import it, the other way around. 我面临的问题是程序中有多个导入,这导致我的程序确实在本地运行(通过执行
python ./__main__.py
,而不是从安装(通过运行pg
)运行)。或者,取决于我导入它的方式,反之亦然。
__main__.py
imports nonfruit.py
: __main__.py
导入nonfruit.py
:
from nonfruit import Nonfruit
nonfruit.py
imports vegetables/carrot.py
: nonfruit.py
进口vegetables/carrot.py
:
import vegetables.carrot
ca = vegetables.carrot.Carrot()
I would like to hear some advice in structuring my project regarding imports, so that it runs both locally and from setuptools installation. 我想在构建有关导入的项目时听到一些建议,以便它既可以在本地运行,也可以从setuptools安装中运行。 For example, should I use absolute imports or relative imports?
例如,我应该使用绝对进口还是相对进口? And should I use
from X import Y
or import XY
? 我应该
from X import Y
还是from X import Y
import XY
?
I found a solution on Jan-Philip Gehrcke's website . 我在Jan-Philip Gehrcke的网站上找到了解决方案。
The instructions are written for use with Python 3, but I applied it to Python 2.7 with success. 这些说明是为与Python 3结合使用而编写的,但是我成功地将其应用于Python 2.7。 The problem I was having originated from my directory becoming a package.
我的问题源于我的目录成为软件包。 Jan advices to create one file to run it from source (
bootstrap-runner.py
) and one file to run it from installation ( bootstrap/__main__.py
). Jan建议创建一个文件来从源代码运行它(
bootstrap-runner.py
),并创建一个文件来从安装bootstrap/__main__.py
运行它( bootstrap/__main__.py
)。 Furthermore, he advices to use explicit relative imports: 此外,他建议使用显式相对导入:
from .X import Y
This will probably be a good guideline in the next applications I'm writing. 在我正在编写的下一个应用程序中,这可能是一个很好的指南。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.