在 python 中自动下载所有必要的库

Downloading automatic all necessary libraries in python

我做了这段代码来测试一些导入:

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

我使用 freeze 创建了一个可执行文件,有时会出现错误 ModuleNotFoundError: No module named:(lib)always is a different lib,我尝试了每个库 运行 pip install (lib) 但不是'没用。 是否存在某种方法来检查是否安装了某些库,如果没有,则自动下载代码中的库?

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

requirements.txt:

PySimpleGUI
psutil
pygetwindow
pyautogui
importlib

使用 freeze 使可执行文件是什么意思?

我认为您指的是 requirements.txt 文件,该文件是在命令行上使用 pip freeze> requirements.txt 生成的,不要忘记删除不必要的 import.You 可以使用 [=14= 下载所有必要的库]

用于检查库和安装自动化

你用import <packagename>

检查
import sys
import subprocess

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

希望对你有所帮助,了解虚拟环境