在Python中将文本值转换为模块类型

rjee0c15  于 2023-01-03  发布在  Python
关注(0)|答案(1)|浏览(207)

我正在尝试使用下面的代码查看这些库是否已经安装在python环境中。

import os
libraries=['pandas','paramico','fnmatch'] #list of libraries to be installed 
for i in libraries:
    print("Checking the library", i ," installation")
    try:
       import i
       print("module ", i ," is installed")
    except ModuleNotFoundError:
       print("module ", i, " is not installed")

数组值没有被转换为模块类型,所有的东西都显示没有安装,所以如何将文本值从数组转换为模块类型。
在上面的示例中,panda和paramico没有安装,但安装了fnmatch。

krugob8w

krugob8w1#

使用importlib.import_module

import os
import importlib

libraries=['pandas','paramico','fnmatch'] #list of libraries to be installed 
for i in libraries:
    print("Checking the library", i ," installation")
    try:
       importlib.import_module(i)
       print("module ", i ," is installed")
    except ModuleNotFoundError:
       print("module ", i, " is not installed")

输出示例:

Checking the library pandas  installation
module  pandas  is installed
Checking the library paramico  installation
module  paramico  is not installed
Checking the library fnmatch  installation
module  fnmatch  is installed

相关问题