How to check if a module is installed in Python and, if not, install it within the code?

后端 未结 7 1966
失恋的感觉
失恋的感觉 2021-01-31 17:35

I would like to install the modules \'mutagen\' and \'gTTS\' for my code, but I want to have it so it will install the modules on every computer that doesn\'t have them, but it

7条回答
  •  南笙
    南笙 (楼主)
    2021-01-31 17:49

    You can check if a package is installed using pkg_resources.get_distribution:

    import pkg_resources
    
    for package in ['mutagen', 'gTTS']:
        try:
            dist = pkg_resources.get_distribution(package)
            print('{} ({}) is installed'.format(dist.key, dist.version))
        except pkg_resources.DistributionNotFound:
            print('{} is NOT installed'.format(package))
    

    Note: You should not be directly importing the pip module as it is an unsupported use-case of the pip command.

    The recommended way of using pip from your program is to execute it using subprocess:

    subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'my_package'])
    

提交回复
热议问题