如果两个 Python 的第三库名字相同,如何去区分?

2015 年 3 月 24 日
 RIcter

python 中有一个 websocket 和 websocket-client,用法都是 import websocket
现在有一个需求是判断 websocket-client 是否安装,有没有 identity 可以判断到底是 websocket-client 还是 websocket?

分分分分分分分分分分分割线线线线线线线线线线线线

另外,有个这样的需求..

try:
    xxx
except (websocket.WebSocketException, sock.error, urllib.xxxx) as e:
    xxx

当 websocket 库不存在的时候如何保证不报错,当安装的时候可以 websocket.WebSocketException 这个错误?最好的保持上述结构,因为结构实在是很难变动的...(好几百行orz)

4229 次点击
所在节点    Python
18 条回复
mikangchan
2015 年 3 月 24 日
前排跪舔/w\
geeklian
2015 年 3 月 24 日
两个库名字一样=.=
不是子集的关系,那就是违规了吧?
est
2015 年 3 月 24 日
try:
import websocket
websocket.特别的method
except:
exit('木有安装')
RIcter
2015 年 3 月 24 日
@est thx,这个我倒是想过,只是想问问有没有别的更好的方法喵QAQ..
tidewind
2015 年 3 月 24 日
print websocket.__name__试试呢
RIcter
2015 年 3 月 24 日
@tidewind 这俩都一样..
Septembers
2015 年 3 月 24 日
print(map(lambda x: getattr(x, 'project_name'), pkg_resources.require('websocket')))

see https://stackoverflow.com/questions/2058802
scys
2015 年 3 月 25 日
将库下载下来,直接修改名字,然后再import~
Septembers
2015 年 3 月 25 日
@scys 客户环境/生产环境 不是想动就能动的
22too
2015 年 3 月 25 日
难道不能as 吗??
import websocket as web
RIcter
2015 年 3 月 25 日
@22too
乃没看懂我的需求…
我是判断 import 的库是不是我想 import 的那个
yegle
2015 年 3 月 25 日
判断 websocket-client 是否安装

这个活读取pip freeze的输出不行吗?或者

from pip install get_installed_distributions
RickGray
2015 年 3 月 25 日
查看 __doc__ :)
22too
2015 年 3 月 25 日
@RIcter 明白了!
Melodic
2015 年 3 月 25 日
楼主看上去好面善
RIcter
2015 年 3 月 25 日
@Melodic 这都能被看粗来!
Madimo
2015 年 3 月 26 日
难道不是自己写个工厂类再封装一层就可以了么...
RIcter
2015 年 3 月 26 日
@Madimo _(:з」∠)_啥

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/179137

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX