如何删除构建产品

Feu*_*mel 7 python build-process setuptools

是否可以自动删除由setup.py基于setuptools的脚本生成的构建产品?

我刚开始使用一个新的Python项目,这是我第一次使用setuptools作为开发人员,所以我可能会遇到问题.当我使用的建设项目python setup.py bdist,三个目录,build,dist和一个结束的.egg-info创建.当我然后运行python setup.py clean它似乎没有做任何事情只是打印这个:

running clean
Run Code Online (Sandbox Code Playgroud)

我已经尝试添加--allclean命令,虽然它确实会删除的一些文件build的目录,它不会删除目录本身或任何文件中的其他两个目录.

我假设这应该很容易,我只是在错误的地方.我已经习惯了这个功能,例如几乎任何项目使用的make地方make cleanmake distclean将删除任何构建产品.

Sim*_*mon 7

标准方法:

distutils.command.clean
Run Code Online (Sandbox Code Playgroud)

清理 setup.py 中的构建目录文档

此命令删除由 build 及其子命令创建的临时文件,如中间编译的目标文件。使用 --all 选项,将删除完整的构建目录。


另一种方法:

这可能不是最好的解决方案:

这个答案下面的评论看来,python setup.py clean --all有时无法删除所有内容(评论中的示例中的 Numpy)。

似乎并非所有 setup.py 脚本都支持 clean。示例:NumPy – kevinarpe 2016 年 6 月 15 日 7:14


您可以remove_tree()在安装脚本中使用该命令:

import glob
remove_tree(['dist', glob.glob('*.egg-info')[0],glob.glob('build/bdist.*')[0]]) 
Run Code Online (Sandbox Code Playgroud)

或者在安装脚本中:

from setuptools import setup
from setuptools.command import install 

class PostInstallCommand(install):

    def run(self):
        import glob
        from distutils.dir_util import remove_tree
        remove_tree(['dist', glob.glob('*.egg-info')[0],glob.glob('build/bdist.*')[0]]) 


setup(name='Some Name',
      version='1.0',
      description='A cross platform library',
      author='Simon',
      platforms = ["windows", "mac", "linux"],
      py_modules = ['UsefulStuff', '__init__'],
      cmdclass = {'install':PostInstallCommand}
     )
Run Code Online (Sandbox Code Playgroud)

我解决它的另一种方法是手动删除所有内容(使用shutilglob):

import shutil, glob
shutil.rmtree('dist')
shutil.rmtree(glob.glob('*.egg-info')[0])
shutil.rmtree(glob.glob('build/bdist.*')[0])
Run Code Online (Sandbox Code Playgroud)

将它添加到安装脚本更难,但使用这个答案,它应该看起来像这样:

from setuptools import setup
from setuptools.command import install 

class PostInstallCommand(install):

    def run(self):
        import shutil, glob
        shutil.rmtree('dist')
        shutil.rmtree(glob.glob('*.egg-info')[0])
        shutil.rmtree(glob.glob('build/bdist.*')[0])
        install.run(self)



setup(name='Some Name',
      version='1.0',
      description='A cross platform library',
      author='Simon',
      platforms = ["windows", "mac", "linux"],
      py_modules = ['UsefulStuff', '__init__'],
      cmdclass = {'install':PostInstallCommand}
     )
Run Code Online (Sandbox Code Playgroud)

cmdclass = {'install'}允许此类在安装后运行。 有关更多详细信息,请参阅此答案

是什么让我想到使用 Shutil?

使用 shutil 的想法来自旧文档

其中一些可以用shutil模块代替吗?

  • 谢谢你,西蒙!你认为这个问题没有表现出足够的内置解决方案是有原因的吗?大多数人在清理方面没有问题吗?我有点想知道是否有其他方法或工具可以满足这种需求,如果我在这里遇到 XY 问题。 (2认同)