2011-09-19 138 views
7

我想使用模块,例如, BeautifulSoup,在我的Python代码,所以我通常将其添加到文件的顶部:仅在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的本地副本:如果dev的

from BeautifulSoup.BeautifulSoup import BeautifulSoup, CData 

但谁使用我的图书馆的Eloper已经在他们的机器上安装了BeautifulSoup?我想修改myscript.py,以便检查是否已安装BeautifulSoup,如果是,请使用标准模块。否则,使用包含的。

使用伪蟒蛇:

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

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

+1

从http://effbot.org/zone/import-confusion.htm摘自:'当Python导入一个模块,它首先检查模块注册表(sys.modules中),以看看模块是否已经导入。如果是这样,Python会按原样使用现有的模块对象。“ – mwan

+0

尝试导入它。如果不起作用,请捕获ImportError并从本地副本导入。将其他名称命名为本地副本(myBeautifulSoup),以便它不隐藏用户安装的模块。 –

+0

@mwan:Ben不需要知道它是否已经*导入*,他需要知道它是否已经*在系统*上。 –

回答

15

通常以下模式用于处理Python中的这种情况。

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

然后:

try: 
    import BeautifulSoup # Standard 
except ImportError: 
    import MyBeautifulSoup as BeautifulSoup # internal distribution