gpt4 book ai didi

python - 使用共享包部署 python 应用程序

转载 作者:行者123 更新时间:2023-11-28 20:54:47 25 4
gpt4 key购买 nike

我在考虑如何安排一个已部署的 python 应用程序,它将有一个

  1. 位于/usr/bin/中的可执行脚本将为在
  2. 中实现的功能提供 CLI
  3. 安装到当前站点包目录所在位置的库。

现在,目前,我的源代码中有以下目录结构:

foo.py
foo/
__init__.py
...

我想这不是最好的做事方式。在开发过程中,一切都按预期工作,但是在部署时,foo.py 中的“from foo import FooObject”代码似乎试图导入 foo.py 本身,这不是我想要的行为。

所以问题是协调这种情况的标准做法是什么?我能想到的一件事是,在安装时,将 foo.py 重命名为 foo,这会阻止它导入自身,但这看起来很尴尬......

我想问题的另一部分是命名挑战。也许调用可执行脚本 foo-bin.py?

最佳答案

This article非常好,并向您展示了一个很好的方法。 Do 列表中的第二项回答了您的问题。

无耻的复制粘贴:

Filesystem structure of a Python project

by Jp Calderone

Do:

  • name the directory something related to your project. For example, if your project is named "Twisted", name the top-level directory for its source files Twisted. When you do releases, you should include a version number suffix: Twisted-2.5.
  • create a directory Twisted/bin and put your executables there, if you have any. Don't give them a .py extension, even if they are Python source files. Don't put any code in them except an import of and call to a main function defined somewhere else in your projects.
  • If your project is expressable as a single Python source file, then put it into the directory and name it something related to your project. For example, Twisted/twisted.py. If you need multiple source files, create a package instead (Twisted/twisted/, with an empty Twisted/twisted/__init__.py) and place your source files in it. For example, Twisted/twisted/internet.py.
  • put your unit tests in a sub-package of your package (note - this means that the single Python source file option above was a trick - you always need at least one other file for your unit tests). For example, Twisted/twisted/test/. Of course, make it a package with Twisted/twisted/test/__init__.py. Place tests in files like Twisted/twisted/test/test_internet.py.
  • add Twisted/README and Twisted/setup.py to explain and install your software, respectively, if you're feeling nice.

Don't:

  • put your source in a directory called src or lib. This makes it hard to run without installing.
  • put your tests outside of your Python package. This makes it hard to run the tests against an installed version.
  • create a package that only has a __init__.py and then put all your code into __init__.py. Just make a module instead of a package, it's simpler.
  • try to come up with magical hacks to make Python able to import your module or package without having the user add the directory containing it to their import path (either via PYTHONPATH or some other mechanism). You will not correctly handle all cases and users will get angry at you when your software doesn't work in their environment.

关于python - 使用共享包部署 python 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/328568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com