Home » Python » Installing python module within code

Installing python module within code

Posted by: admin November 1, 2017 Leave a comment

Questions:

I need to install a package from PyPi straight within my script.
Maybe there’s exists module or distutils (distribute, pip) ability which allows me just execute something like pypi.install('requests') and requests will be installed into my virtualenv, and I should not type pip install requests in my shell?

Answers:

You can also use something like:

import pip

def install(package):
    pip.main(['install', package])

# Example
if __name__ == '__main__':
    install('argh')

Questions:
Answers:

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.

Questions:
Answers:

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).

Questions:
Answers:

This should work:

import subprocess

def install(name):
    subprocess.call(['pip', 'install', name])

Questions:
Answers:

I hope this question is still valid.
I did the above something like this:

    import sys
    import os
    import site 

    try:
       import pip
    except ImportError:
       print "installing pip"
       cmd = "sudo easy_install pip"
       os.system(cmd)
       reload(site)

    try: 
       import requests
    except ImportError:
       print "no lib requests"
       import pip
       cmd = "sudo pip install requests"
       print "Requests package is missing\nPlease enter root password to install required package"
       os.system(cmd)
       reload(site)

the second try block can be written in the else part of the first try block as well, however in my problem statement I has to write two seperate blocks.

Questions:
Answers:

you could always download

import os

then right all the terminal commands to download it from there.

like

while True:

code = input("")

os.system("code")

whatever it is i’m not sure but if you don’t even know how to do it in terminal how are you gonna do it in python.