简体   繁体   English

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

[英]Import a module in Python only if it doesn't already exist

I want to use a module, eg BeautifulSoup, in my Python code, so I usually add this to the top of the file: 我想在我的Python代码中使用一个模块,例如BeautifulSoup,所以我通常将它添加到文件的顶部:

from BeautifulSoup import BeautifulSoup

However, when I distribute the module I'm writing, others may not have BeautifulSoup, so I'll just include it in my directory structure like so: 但是,当我分发我正在编写的模块时,其他人可能没有BeautifulSoup,所以我只是将它包含在我的目录结构中,如下所示:

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

Now, my modified myscript.py file will look like this at the top to reference the local copy of BeautifulSoup: 现在,我修改的myscript.py文件在顶部看起来像这样引用BeautifulSoup的本地副本:

from BeautifulSoup.BeautifulSoup import BeautifulSoup, CData

But what if the developer who uses my library already has BeautifulSoup installed on their machine? 但是如果使用我的库的开发人员已经在他们的机器上安装了BeautifulSoup呢? I want to modify myscript.py so that it checks to see if BeautifulSoup is already installed, and if so, use the standard module. 我想修改myscript.py,以便检查是否已安装BeautifulSoup,如果已安装,请使用标准模块。 Otherwise, use the included one. 否则,请使用附带的一个。

Using Pseudo-python: 使用Pseudo-python:

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

Is this possible? 这可能吗? If so, how? 如果是这样,怎么样?

Usually the following pattern is used to handle this situation in Python. 通常,以下模式用于在Python中处理这种情况。

First rename your BeautifulSoup module something else, eg MyBeautifulSoup 首先将您的BeautifulSoup模块重命名为其他内容,例如MyBeautifulSoup

Then: 然后:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM