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

后端 未结 7 1964
失恋的感觉
失恋的感觉 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:52

    EDIT - 2020/02/03

    The pip module has updated quite a lot since the time I posted this answer. I've updated the snippet with the proper way to install a missing dependency, which is to use subprocess and pkg_resources, and not pip.

    To hide the output, you can redirect the subprocess output to devnull:

    import sys
    import subprocess
    import pkg_resources
    
    required = {'mutagen', 'gTTS'}
    installed = {pkg.key for pkg in pkg_resources.working_set}
    missing = required - installed
    
    if missing:
        python = sys.executable
        subprocess.check_call([python, '-m', 'pip', 'install', *missing], stdout=subprocess.DEVNULL)
    

    Like @zwer mentioned, the above works, although it is not seen as a proper way of packaging your project. To look at this in better depth, read the the page How to package a Python App.

提交回复
热议问题