0

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?

1

2 Answers 2

2

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>'])
Sign up to request clarification or add additional context in comments.

4 Comments

I use cx_Freeze to make my executables, i know that exist PyInstaller but no works in my pc =(
I edited my post, you talking about like this?
Well now look like you had confused me with your problem heading.
I'm confused too, but, my problem is done, thanks haha
0

(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

Comments

Your Answer

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