最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Python中如何动态检测是否安装某个库

Python crifan 2898浏览 0评论

折腾:

【记录】尝试用Python操作PhantomJS+Selenium去模拟购物操作

期间,调用自己的Python库:

crifanLib.py

结果发现之前写的代码,不够智能:

必须要安装chardet(和其他库)才能用

否则报错:

所以希望实现,别处看到的,动态监测是否安装了某个库

决定后面代码是否可用。

python dynamic import

python – How to dynamically import modules? – Stack Overflow

Dynamic module import in Python – Stack Overflow

dynamic import – Dynamically importing Python module – Stack Overflow

Advanced Python – How to Dynamically Load Modules or Classes | The Mouse Vs. The Python

好像可以用:

try

import

ImportError

31.5. importlib — The implementation of import — Python 3.6.3 documentation

【总结】

然后用:

try:
    import chardet
except ImportError:
    print “crifanLib: Can not found lib chardet”
try:
    from BeautifulSoup import BeautifulSoup, Tag, CData
except ImportError:
    print “crifanLib: Can not found lib BeautifulSoup”

即可实现:当导入chardet,BeautifulSoup等库失败时,程序也不会挂

而调用者自己知道没有这些库,所以后续的用到chardet的函数,也不会去调用。

就基本上实现此处的目的了。

转载请注明:在路上 » 【已解决】Python中如何动态检测是否安装某个库

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.175 seconds, using 22.02MB memory