laitimes

One skill a day: Two tips in setup.py

One skill a day: Two tips in setup.py

When you're publishing a Python package yourself, these two tips may be useful to you.

Execute the code after pip is installed

In today's fan group of the official account, a student asked:

One skill a day: Two tips in setup.py

This student developed a Python package by himself, which generates some temporary files when installed with pip. He wants to be able to clean up these temporary files automatically after the installation is complete.

To achieve this requirement, you can use the built-in setuptools in Python. Here's the code:

import os
from setuptools import setup, find_packages
from setuptools.command.install import install

class CustomInstallCommand(install):
    """自定义安装命令,执行标准安装后跟自定义代码。"""
    def run(self):
        install.run(self)
        print("执行自定义安装后的代码...")
        os.remove('需要删除的文件1路径')
        os.remove('需要删除的文件2路径')
        print('这里可以写任意代码')

setup(
    name='your_package_name',
    version='0.1',
    packages=find_packages(),
    cmdclass={
        'install': CustomInstallCommand,
    },
)           

When you upload the code to Pypi, the user still uses pip install xxx to install the package. Once the installation is complete, the temporary files can be deleted automatically.

Additional dependencies

When you install some third-party libraries, you may see its installation instructions, which ask you to write like this:

pip install "xxx[yyy]"           

As shown in the figure below:

One skill a day: Two tips in setup.py

What does this mean? It's actually called optional extras. There are some powerful third-party libraries that need to install a lot of dependencies. But if I only need to use a particular feature of it, then I really only need to install the dependencies that that the feature requires. There is no need to install all dependencies at all.

In this case, additional dependencies can be used. In the setup.py, add extras_require parameters:

setup(
    name='your_package_name',
    version='0.1',
    packages=find_packages(),
    install_requires=['requests']
    extras_require={
     'excel': ['pandas>=1.20.0'],
     'lxml': ['lxml'],
     'all': ['pandas>=1.20.0', 'lxml']
    },
)           

Then when the user installs the package with pip install xxx, only one dependency of requests will be installed by default. When pip install "xxx[lxml]" is used, requests and lxml are installed. When pip install "xxx[all]" is used, requests, lxml, and pandas are installed.