0

I'm working on a project which I should install the same code in different raspberry pis, which led me to think that using the same .venv for every one of them is probably not a good idea and could lead me to some problems.

Then I thought about creating a script to install every pip modules that I need in every one of them when I set them up for the first time. Is there any way to create a script that ensures that the module was properly installed? Being that the case, is there a better choice than a bash script?

d3lux1999
  • 26
  • 4

2 Answers2

0

You have two options:-

  • Either: using a child process:
from subprocess import Popen as popen
import sys
def install_pip_module(module):
    popen([sys.executable, '-m', '-pip', '-install', module]).wait()
  • Or: using the actual pip cli parser class within python itself:
# pip install + remove from python itself not a subprocess ! #

#import the pip module
from pip._internal.cli.main import main as pip_entry_point

#install a module
pip_entry_point(['install', 'module_name'])

#uninstall a module without prompot for yes
pip_entry_point(['uninstall', 'module_name', '-y'])

Personally, I prefer the second method as it doesn't use a child process;
However, the first option is recommended by pip module authors.


Then: you should create a requirements.txt file manually
or using pip freeze > requirements.txt
then pass these arguments to pip install -r path/to/requirements.txt so that it installs them one by one.
OR
you can iterate through a List of modules using a for loop.

ibrahem
  • 288
  • 2
  • 9
0

I saw this answer to check if a module is well installed from within the python script here : How to check if a module is installed in Python and, if not, install it within the code?

Here is the basic gist of it:

The pip module has updated quite a lot since the time I posted this answer. I've updated the snippet with the proper way to install a missing dependency, which is to use subprocess and pkg_resources, and not pip.

To hide the output, you can redirect the subprocess output to devnull:

import sys
import subprocess
import pkg_resources

required = {'mutagen', 'gTTS'}
installed = {pkg.key for pkg in pkg_resources.working_set}
missing = required - installed

if missing:
    python = sys.executable
    subprocess.check_call([python, '-m', 'pip', 'install', *missing], stdout=subprocess.DEVNULL)

The main issue here for me would be that the dependencies are within the code.You could solve this by having the variable required in the above code that will parse your requirement.txt to extract the right packages that are needed for your program.

I hope that this will help you.