【问题标题】:How to depends of a system command with python/distutils?如何使用 python/distutils 依赖系统命令?
【发布时间】:2023-04-11 01:21:01
【问题描述】:

我正在寻找一种最优雅的方式来通知我的库的用户他们需要一个特定的 unix 命令来确保它能够正常工作...

我的库何时引发错误:

  • 安装?
  • 当我的应用调用命令时?
  • 在导入我的库时?
  • 两者都有?

还有你应该如何检测命令丢失(if not commands.getoutput("which CommandIDependsOn"): raise Exception("you need CommandIDependsOn"))。

我需要建议。

【问题讨论】:

  • 你不能假设安装在目标操作系统上。
  • ^^,我认为这是个玩笑。但如果不是,我可以改用命令。 command -v 具有与 which 相同的行为,但它是 POSIX 标准的一部分。

标签: python command packaging distutils


【解决方案1】:

IMO,最好的方法是在安装时检查用户是否有这个特定的 *nix 命令。

如果您使用 distutils 分发您的软件包,为了安装它,您必须这样做:

python setup.py 构建 python setup.py 安装

或者干脆

python setup.py install(在这种情况下 python setup.py build 是隐式的)

要检查是否安装了 *nix 命令,您可以像这样在 setup.py 中子类化构建方法:

from distutils.core import setup
from distutils.command.build import build as _build

class build(_build):

    description = "Custom Build Process"
    user_options= _build.user_options[:]
    # You can also define extra options like this : 
    #user_options.extend([('opt=', None, 'Name of optionnal option')])

    def initialize_options(self):   

        # Initialize here you're extra options... Not needed in your case
        #self.opt = None
        _build.initialize_options(self)

    def finalize_options(self):
        # Finalize your options, you can modify value
        if self.opt is None :
            self.opt = "default value"

        _build.finalize_options(self)

    def run(self):
        # Extra Check
        # Enter your code here to verify if the *nix command is present
        .................

        # Start "classic" Build command
        _build.run(self)

setup(
        ....
        # Don't forget to register your custom build command
        cmdclass         = {'build' : build},
        ....
     )

但是如果用户在安装包后卸载了所需的命令怎么办?要解决这个问题,唯一“好的”解决方案是使用打包系统,例如 deb 或 rpm,并在命令和您的包之间建立依赖关系。

希望对你有帮助

【讨论】:

  • 你是对的,我认为 Aaron Gallagher 的答案是一个好答案。因为我正在寻找的命令通常预装在许多发行版中......
  • 您的代码中存在错误。您必须复制 build.install_options 列表,否则您对其进行的任何修改都会编辑原始列表!
【解决方案2】:

我根本不会有任何支票。记录您的库需要此命令,如果用户尝试使用库中需要它的任何部分,则运行该命令的任何内容都会引发异常。应该仍然可以导入您的库并使用它,即使只提供了一部分功能。

(PS:commands 是旧的和损坏的,不应该在新代码中使用。subprocess 是热门的新东西。)

【讨论】:

  • Thanx Aaron,(为了兼容性,我通常都在 try catch 中导入)我的 lib 只是关于包装 gnu-screen,所以没有它它会更少,(pypi 上的 screenutils)。我想我会按照你的建议去做。
猜你喜欢
  • 1970-01-01
  • 2011-11-06
  • 2014-09-07
  • 1970-01-01
  • 2014-01-23
  • 2021-01-08
  • 2012-05-07
  • 2014-05-21
  • 2013-06-26
相关资源
最近更新 更多