使用distutils / setuptools在安装后执行Python脚本 [英] Execute a Python script post install using distutils / setuptools
问题描述
我正在尝试按照如何使用简单的安装后脚本扩展distutils?。该任务应该在已安装的lib目录中执行Python脚本 。此脚本会生成已安装软件包所需的其他Python模块。
I'm trying to add a post-install task to Python distutils as described in How to extend distutils with a simple post install script?. The task is supposed to execute a Python script in the installed lib directory. This script generates additional Python modules the installed package requires.
我的第一次尝试如下:
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},
)
此方法有效,但据我所知有两个缺陷:
This approach works, but as far as I can tell has two deficiencies:
- 如果用户使用的Python解释器不是从
PATH
中拾取的,则安装后脚本将使用不同的解释器执行,该解释器可能会导致问题。 - 对于空运行等并不安全。我可以通过将其包装在函数中来进行补救并使用
distutils.cmd.Command.execute
调用它。
- If the user has used a Python interpreter other than the one picked up from
PATH
, the post install script will be executed with a different interpreter which might cause a problem. - It's not safe against dry-run etc. which I might be able to remedy by wrapping it in a function and calling it with
distutils.cmd.Command.execute
.
怎么可能我可以改善解决方案吗?有推荐的方法/最佳做法吗?我想尽可能避免引入其他依赖项。
How could I improve my solution? Is there a recommended way / best practice for doing this? I'd like to avoid pulling in another dependency if possible.
推荐答案
解决这些缺陷的方法是:
The way to address these deficiences is:
- 从
获取执行
。setup.py
的Python解释器的完整路径sys.executable -
从
distutils.cmd.Command
继承的类(例如distutils.command.install.install
(我们在这里使用)实现execute
方法,该方法在安全方式,即尊重空转标志。
- Get the full path to the Python interpreter executing
setup.py
fromsys.executable
. Classes inheriting from
distutils.cmd.Command
(such asdistutils.command.install.install
which we use here) implement theexecute
method, which executes a given function in a "safe way" i.e. respecting the dry-run flag.
请注意, -干运行
选项当前已损坏,并且仍然无法正常工作。
Note however that the --dry-run
option is currently broken and does not work as intended anyway.
我得到了以下解决方案:
I ended up with the following solution:
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},
)
请注意,我使用类名为我的派生类安装
,因为这就是 python setup.py --help-commands
将使用的东西。
Note that I use the class name install
for my derived class because that is what python setup.py --help-commands
will use.
这篇关于使用distutils / setuptools在安装后执行Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!