我正在尝试向 Python distutils 添加一个安装后任务,如 How to extend distutils with a simple post install script? 中所述。 .该任务应该在已安装的 lib 目录中执行 Python 脚本。此脚本会生成已安装包所需的其他 Python 模块。
我的第一次尝试如下:
from distutils.core import setup
from distutils.command.install import install
class post_install(install):
def run(self):
install.run(self)
from subprocess import call
call(['python', 'scriptname.py'],
cwd=self.install_lib + 'packagename')
setup(
...
cmdclass={'install': post_install},
)
这种方法有效,但据我所知有两个不足:
- 如果用户使用的 Python 解释器不是从
PATH
获取的解释器,则安装后脚本将使用 不同的 解释器执行,这可能会导致问题. - 它对空运行等不安全,我可以通过将其包装在一个函数中并使用
distutils.cmd.Command.execute
调用它来补救。
如何改进我的解决方案?有推荐的方法/最佳实践吗?如果可能的话,我想避免引入另一个依赖项。
最佳答案
解决这些不足的方法是:
- 从
sys.executable
获取执行setup.py
的 Python 解释器的完整路径。 继承自
distutils.cmd.Command
的类(比如我们这里使用的distutils.command.install.install
)实现execute
方法,它以“安全的方式”执行给定的功能,即尊重空运行标志。但请注意 the
--dry-run
option is currently broken并且无论如何都不能按预期工作。
我最终得到了以下解决方案:
import os, sys
from distutils.core import setup
from distutils.command.install import install as _install
def _post_install(dir):
from subprocess import call
call([sys.executable, 'scriptname.py'],
cwd=os.path.join(dir, 'packagename'))
class install(_install):
def run(self):
_install.run(self)
self.execute(_post_install, (self.install_lib,),
msg="Running post install task")
setup(
...
cmdclass={'install': install},
)
请注意,我将类名 install
用于派生类,因为这是 python setup.py --help-commands
将使用的。
关于python - 使用 distutils/setuptools 执行 Python 脚本安装后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17806485/