Mi Po
Mi Po

Reputation: 1203

How to install modules locally from python code

I have some python code test.py

It imports some modules such as import numpy as np

I want to be able to run this code using python test.py

However it fails because module numpy is not installed.

Is it possible to add a line to python code to automatically install a module if its not already installed?

Additionally is it possible to make the module install in the local folder to the test.py file, like a .dll in c++

Thanks

Upvotes: 2

Views: 1906

Answers (2)

furas
furas

Reputation: 142641

You can aloways uses

os.system("pip install numpy") 

or

os.system("python -m pip install numpy"). 

or some functions from module subprocess to better control it.

import subprocess

subprocess.run("python -m pip install numpy", shell=True)

You could use try/except for this

try
    import numpy
except:
    os.system("python -m pip install numpy")
    import numpy

Eventually you can import pip because it is Python module and then you use it in your code. But for more details you would have to find documentation for pip module


BTW: I found example with import pip in Installing python module within code

Upvotes: 3

Swetank Poddar
Swetank Poddar

Reputation: 1291

Usually when you use python's virtual environment (Virtualenv) it installs those libraries locally in a specific folder.

You can read more about it in this stackoverflow answer.

To install any library you could do the following thing:

import os # This step is important
os.system("pip install yourModule")

This will install the module if it doesn't exists! (Ps: it doesn't throw any error if it's already present, so there's no need for error handling as well!)

Upvotes: 1

Related Questions