How to delete all dependent modules of python?

Statement: This article was first published in my Zhihu article. Please state the source of the article according to the specifications. Thank you!

After you complete the installation of xxx module with pip install xxx, you will find that it will automatically install the modules that xxx depends on. Finally, the following contents will be displayed:

(the following operations take the pipenv module as an example)

pip is really Nice! You can install all the modules for us at once. You don't have to manually install pip one by one!

If you want to delete pipenv one day, you can use pip uninstall -y pipenv to delete pipenv, which is also very simple.

pip uninstall -y pipenv

But, "emperor, do you remember the summer rain lotus on the Bank of Daming Lake"?

Ah, no, do you still remember that pip helped you install the family bucket that pipenv depends on when you installed pipenv before?

So, at this time, do you need to delete the dependent package of pipenv?

If you need to delete, sorry, pip doesn't provide instructions to delete dependent packages. I thought about it. In fact, this is also for your convenience. You don't have to download the dependency package when you install pipenv next time.

If you have to delete it, there are two ways:

Method 1

pip show pipenv

The installation information of pipenv will be displayed, as shown in the following figure:

See the requirements in the penultimate line. Those are the dependent packages of pipenv.

You can manually delete it with pip uninstall -y xxx in turn!

Note: do not delete PIP and setuptools. These two are needed for pip to install xxx module!
Note: do not delete PIP and setuptools. These two are needed for pip to install xxx module!
Note: do not delete PIP and setuptools. These two are needed for pip to install xxx module!

Method 2

Write a script to delete dependent packages in batch!

This is the focus of my article today.
This is the focus of my article today.
This is the focus of my article today.

Come 'on, every buddies! The following content is the focus of this article. Everyone has read it carefully~

import os


# White list to avoid being deleted by mistake
WHITELIST = ['pip', 'setuptools']
# List of modules to be deleted
REMOVELIST = []


def get_requires(module_name):
    """
    View the dependencies of a module
    :param module_name: Module name
    :return: module_name List of dependent modules
    """
    with os.popen('pip show %s' % module_name) as p:
        requires = p.readlines()
        if not len(requires):
            return []

        reqs = ''
        for line in requires:
            if not line.startswith('Requires:'):
                continue
            reqs = line.strip()
        
        requires = reqs.split(':')[-1].replace(' ', '').strip()
        if requires:
            requires = requires.split(',')
        else:
            requires = []
        return requires


def get_required_bys(module_name):
    """
    View which modules a module depends on
    :param module_name: Module name
    :return: module_name List of dependent modules
    """
    with os.popen('pip show %s' % module_name) as p:
        req_by = p.readlines()
        if not len(req_by):
            return []

        required = ''
        for line in req_by:
            if not line.startswith('Required-by:'):
                continue
            required = line.strip()
        
        req_by = required.split(':')[-1].replace(' ', '').strip()
        if req_by:
            req_by = req_by.split(',')
        else:
            req_by = []
        return req_by


def install(name):
    os.system(f'pip install {name}')


def get_all_requires(module_name):
    """
    Recursively get all the dependencies of a module
    :param module_name: Module name
    :return: None
    """
    dependents = get_requires(module_name)
    for package in dependents:
        if package in WHITELIST:
            #print(f'[{package}] in white list')
            continue
        get_all_requires(package)
    REMOVELIST.append(module_name)


def remove(module_name):
    print('Scanning packages...')
    get_all_requires(module_name)
    s_packages =  ','.join(REMOVELIST)
    print(f'[INFO]Found packages: {s_packages}\n')

    for package in REMOVELIST:
        req_bys = get_required_bys(package)
        print('[INFO]removing:', package)
        #print(package, 'is required by:', req_bys)
        flag = True
        for req_by in req_bys:
            if req_by not in REMOVELIST:
                flag = False
                print(f'[NOTICE]As "{package}" is required by "{req_by}" which is not in {REMOVELIST}, skipped...\n')
                break
        if flag:
            print('\n')
            #os.system('pip uninstall -y %s' % package)


if __name__ == '__main__':
    pkg_name = input('Please enter the third-party module package to uninstall: ')
    #install(pkg_name)
    remove(pkg_name)

Next, run the code and try it!

Failed to delete successfully?

Oh, oh, remember to put #os You can remove the phrase "package # s" from the front of "package"!

Finally, if the script runs successfully, remember to pay attention to me, then collect this article and give me a praise! Never reward~

Keywords: Python Programmer

Added by adt2007 on Thu, 03 Mar 2022 06:32:54 +0200