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

2
  • 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 Commented Jan 2, 2020 at 22:26
  • thanks, you can post as answer if you like Commented Jan 2, 2020 at 22:29

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Is there any difference between using subprocess.run and os.system?
using functions from module subprocess you can better control it. You can get output, or error code.
I'm sorry but what do you mean by control it better?
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.
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!)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.