3

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

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

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

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

我需要建议。

4

2 回答 2

5

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

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

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

或者干脆

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},
        ....
     )

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

希望这可以帮助

于 2010-08-12T12:37:36.827 回答
4

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

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

于 2010-08-12T09:00:23.137 回答