如何使用 python/distutils 依赖系统命令?

chr*_*e31 3 python command packaging distutils

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

什么时候是我的 lib 引发错误的最佳时机:

  • 安装 ?
  • 当我的应用程序调用命令时?
  • 在导入我的 lib 时?
  • 两个都?

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

我需要建议。

ohe*_*ohe 5

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

如果您使用 distutils 分发您的软件包,为了安装它,您必须执行以下操作:

python setup.py build python setup.py install

或者干脆

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

要检查 *nix 命令是否已安装,您可以在 setup.py 中子类化 build 方法,如下所示:

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},
        ....
     )
Run Code Online (Sandbox Code Playgroud)

但是如果用户在安装包后卸载所需的命令呢?要解决这个问题,唯一“好的”解决方案是使用诸如 deb 或 rpm 之类的打包系统,并在命令和包之间添加依赖项。

希望这可以帮助