2

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

Mi Po
  • 1,123
  • 2
  • 12
  • 21
  • 1
    you can aloways uses `os.system("pip install numpy")` or `os.system("python -m pip install 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 – furas Jan 02 '20 at 22:26
  • thanks, you can post as answer if you like – Mi Po Jan 02 '20 at 22:29

2 Answers2

3

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

furas
  • 134,197
  • 12
  • 106
  • 148
  • Is there any difference between using subprocess.run and os.system? – Swetank Poddar Jan 02 '20 at 22:36
  • 1
    using functions from module `subprocess` you can better control it. You can get output, or error code. – furas Jan 02 '20 at 22:37
  • I'm sorry but what do you mean by control it better? – Swetank Poddar Jan 02 '20 at 22:38
  • 1
    with `output = subprocess.check_output()` you can assing displayed text to variable `output` and you can save it in log file to keep information if three was problem to install - and user can see it later. Using `exit_code = subprocess.call()` you can get code which returns some programs to recognize if there was problem to run program. – furas Jan 02 '20 at 22:42
1

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

Swetank Poddar
  • 1,257
  • 9
  • 23