Installing python module within code

前端 未结 7 1190
孤独总比滥情好
孤独总比滥情好 2020-11-21 23:31

I need to install a package from PyPi straight within my script. Maybe there\'s some module or distutils (distribute, pip etc.) featur

相关标签:
7条回答
  • 2020-11-22 00:04

    for installing multiple packages, i am using a setup.py file with following code:

    import sys
    import subprocess
    import pkg_resources
    
    required = {'numpy','pandas','<etc>'} 
    installed = {pkg.key for pkg in pkg_resources.working_set}
    missing = required - installed
    
    
    if missing:
        # implement pip as a subprocess:
        subprocess.check_call([sys.executable, '-m', 'pip', 'install',*missing])
    
    0 讨论(0)
  • 2020-11-22 00:06

    You define the dependent module inside the setup.py of your own package with the "install_requires" option.

    If your package needs to have some console script generated then you can use the "console_scripts" entry point in order to generate a wrapper script that will be placed within the 'bin' folder (e.g. of your virtualenv environment).

    0 讨论(0)
  • 2020-11-22 00:07

    If you want to use pip to install required package and import it after installation, you can use this code:

    def install_and_import(package):
        import importlib
        try:
            importlib.import_module(package)
        except ImportError:
            import pip
            pip.main(['install', package])
        finally:
            globals()[package] = importlib.import_module(package)
    
    
    install_and_import('transliterate')
    

    If you installed a package as a user you can encounter the problem that you cannot just import the package. See How to refresh sys.path? for additional information.

    0 讨论(0)
  • 2020-11-22 00:13

    This should work:

    import subprocess
    
    def install(name):
        subprocess.call(['pip', 'install', name])
    
    0 讨论(0)
  • 2020-11-22 00:14

    You can also use something like:

    import pip
    
    def install(package):
        if hasattr(pip, 'main'):
            pip.main(['install', package])
        else:
            pip._internal.main(['install', package])
    
    # Example
    if __name__ == '__main__':
        install('argh')
    
    0 讨论(0)
  • 2020-11-22 00:16

    i added some exception handling to @Aaron's answer.

    import subprocess
    import sys
    
    try:
        import pandas as pd
    except ImportError:
        subprocess.check_call([sys.executable, "-m", "pip", "install", 'pandas'])
    finally:
        import pandas as pd
    
    0 讨论(0)
提交回复
热议问题