user15785950
user15785950

Reputation:

How to automatically download/install all the necessary libraries in python?

I wrote this code to test some imports:

import fnmatch
import os
import psutil
import pygetwindow as window
from time import sleep
import win32api
import PySimpleGUI as pys
import pyautogui as py
from time import sleep
import webbrowser
import winsound
import importlib.util
from random import randint
from datetime import date
import locale

layout = [
    [pys.Text(f'Complete =)', size=(25, 0))],
]
jan = pys.Window('Test', layout=layout, finalize=True)
jan.read()

I then made an executable using freeze, and sometimes the following error appears:

ModuleNotFoundError: No module named: (lib)

It's always a different (lib). I tried to run pip install (lib) for each (lib) but that didn't work.

Is there some way to check if some (lib) is installed and if it isn't, automatically download that (lib) in code?

Upvotes: 0

Views: 894

Answers (2)

Rishu Pandey
Rishu Pandey

Reputation: 438

When you say "making executable using freeze", I think you are referring to a requirements.txt file, which is generated by doing pip freeze> requirements.txt on the command line (and don't forget to remove the unnecessary imports).

You can download all the necessary libraries by doing

pip install -r requirements.txt

To check if a library is installed and automatically install it, you check by using import <packagename>

import sys
import subprocess

try:
    import <packagename>
except Exception as e:
    subprocess.check_call(
        [sys.executable, '-m', 'pip', 'install', '<packagename>'])

Upvotes: 2

Gino Mempin
Gino Mempin

Reputation: 29598

(This is a copy of the OP's solution, reposted it from the question into an actual answer)
(It was copied from revision: https://stackoverflow.com/revisions/68274500/2)


Here is the changed code:

import sys
import subprocess

packages = []
file = open('requirements.txt', 'r')
for lines in file:
    packages.append(lines)
file.close()

for library in packages:
    try:
        import library
    except Exception as e:
        library= library.replace("\n", "")
        subprocess.check_call(
            [sys.executable, '-m', 'pip', 'install', library]
        )

import pygetwindow as window
import PySimpleGUI as pys
import pyautogui as py
import importlib.util
import psutil

layout = [
    [pys.Text(f'Complete =)', size=(25, 0))],
]
jan = pys.Window('Test', layout=layout, finalize=True)
jan.read()

Here is the requirements.txt:

PySimpleGUI
psutil
pygetwindow
pyautogui
importlib

Upvotes: 0

Related Questions