仅当Python中的模块尚不存在时才导入该模块

时间:2011-09-19 22:31:20

标签: python module

我想使用一个模块,例如BeautifulSoup,在我的Python代码中,所以我通常将它添加到文件的顶部:

from BeautifulSoup import BeautifulSoup

然而,当我分发我正在编写的模块时,其他人可能没有BeautifulSoup,所以我只是将它包含在我的目录结构中,如下所示:

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----         9/19/2011   5:45 PM            BeautifulSoup
-a---         9/17/2011   8:06 PM       4212 myscript.py

现在,我修改过的myscript.py文件在顶部看起来像这样引用BeautifulSoup的本地副本:

from BeautifulSoup.BeautifulSoup import BeautifulSoup, CData

但是如果使用我的库的开发人员已经在他们的机器上安装了BeautifulSoup呢?我想修改myscript.py,以便检查是否已安装BeautifulSoup,如果已安装,请使用标准模块。否则,请使用附带的。

使用Pseudo-python:

if fBeautifulSoupIsInstalled:
    from BeautifulSoup import BeautifulSoup, CData
else:
    from BeautifulSoup.BeautifulSoup import BeautifulSoup, CData

这可能吗?如果是这样,怎么样?

1 个答案:

答案 0 :(得分:15)

通常在Python中使用以下模式来处理这种情况。

首先将您的BeautifulSoup模块重命名为其他内容,例如MyBeautifulSoup

然后:

try:
    import BeautifulSoup # Standard
except ImportError:
    import MyBeautifulSoup as BeautifulSoup # internal distribution
相关问题