英文:
How to use python to check for and install library's
问题
以下是翻译好的部分:
"Is there a way to get this to work as every time I run it, It Won't give me an output, just 'PRESS ANY KEY TO CONTINUE...'
as this is currently a test to read the modules I would like it to print the results as well
all help is appreciated
Import the necessary packages
import pip
Create a list of packages to install
packages_to_install = ["numpy", "pandas", "matplotlib"]
List all of the installed packages
installed_packages = pip.freeze()
Compare the list of installed packages to the list of packages to install
for package in packages_to_install:
if package not in installed_packages:
# Print the List of uninstalled packages
print(package)"
英文:
Is there a way to get this to work as every time I run it, It Won't give me a output, just "PRESS ANY KEY TO CONTINUE..."
<br>
as this is currently a test to read the modules I would like it to print the results as well
all help is appreciated
# Import the necessary packages
import pip
# Create a list of packages to install
packages_to_install = ["numpy", "pandas", "matplotlib"]
# List all of the installed packages
installed_packages = pip.freeze()
# Compare the list of installed packages to the list of packages to install
for package in packages_to_install:
if package not in installed_packages:
# Print the List of uninstalled packages
print(package)
答案1
得分: 0
试试这个:
import importlib
import subprocess
import sys
packages_to_install = ["numpy", "pandas", "matplotlib"]
def check_and_install_packages(packages):
for package in packages:
try:
importlib.import_module(package)
print(f"{package} 已安装。")
except ImportError:
print(f"{package} 未安装,正在安装...")
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
print(f"{package} 安装成功。")
# 检查并安装需要的包
check_and_install_packages(packages_to_install)
# 现在你的脚本可以安全地使用已安装的包
英文:
try this:
import importlib
import subprocess
import sys
packages_to_install = ["numpy", "pandas", "matplotlib"]
def check_and_install_packages(packages):
for package in packages:
try:
importlib.import_module(package)
print(f"{package} is already installed.")
except ImportError:
print(f"{package} is not installed. Installing...")
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
print(f"{package} installed successfully.")
# Check and install packages if needed
check_and_install_packages(packages_to_install)
# Rest of your script can now safely use the installed packages
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论