[英]How to import 3rd party module to python if its name is taken?
I want to use this class: google-mail-oauth2-tools but if i'll do something like import oauth2
the imported class would be python-oauth2 which is deprected and doesn't support oauth2 )even though the name is oauth2) How can I use google module ? 我想使用此类: google-mail-oauth2-tools,但如果我要执行类似
import oauth2
则导入的类将是python-oauth2 ,这是不受欢迎的,并且不支持oauth2),即使名称是oauth2)如何我可以使用Google模块吗? do I need to install it first? 我需要先安装它吗?
Looking at the docs you linked , it looks like the Google Mail oauth2
module is meant to be downloaded and used in-place. 查看您链接的文档 ,就好像Google Mail
oauth2
模块是就地下载和使用的。
You can, of course, install it… but you can't have two (top-level) modules installed with the same name, so you'd have to uninstall python-oauth2
first. 当然,您可以安装它…但是您不能安装两个具有相同名称的(顶层)模块,因此您必须先卸载
python-oauth2
。
But if you just use it in-place, in Python 2.7, you can have an oauth2.py
in one directory and one in the stdlib. 但是,如果仅在Python 2.7中就地使用它,则可以在一个目录中拥有一个
oauth2.py
,在stdlib中拥有一个。 Whichever one you import first will "win"; 无论您先导入哪个,都将“获胜”; any subsequent attempts to
import oauth2
will get the first one. 随后的任何
import oauth2
尝试都将获得第一个。
To force it to import the right one (in a way that will also work for older Python 2.x and for Python 3.x), you may want to use the imp
module to give it the path explicitly. 要强制其导入正确的路径(以同样适用于较旧的Python 2.x和Python 3.x的方式),您可能需要使用
imp
模块来明确为其提供路径。
For example, if you plan to put oauth2.py
right alongside the script that imports it, instead of just import oauth2
, do: 例如,如果您打算将
oauth2.py
放在导入它的脚本旁边,而不是仅仅import oauth2
,请执行以下操作:
script_path = os.path.abspath(os.path.dirname(__file__))
f, path, desc = imp.find_module('oauth2', [script_path])
oauth2 = imp.load_module('oauth2', f, path, desc)
… although in some situations, you can get away with cheating by assuming the current working directory is the script directory, and/or by permanently munging sys.path
, etc., so you can simplify it in various different ways—ultimately, if it's safe, just this: …尽管在某些情况下,您可以通过假设当前工作目录为脚本目录和/或通过永久修改
sys.path
等来逃避作弊,因此您可以通过各种不同的方式对其进行简化—如果是安全,仅此:
sys.path = ['.'] + sys.path
import oauth2
Still, I would consider doing one of the following for safety (and readability): 不过,出于安全性(和可读性)考虑,我会考虑执行以下操作之一:
python-oauth2
. python-oauth2
。 oauth2.py
to something else, like google_oauth2.py
, and then import google_oauth2
. oauth2.py
重命名为其他名称,例如google_oauth2.py
,然后import google_oauth2
。 oauth2.py
into a package, so you can, eg, import googletools.oauth2
. oauth2.py
放入一个包中,以便例如import googletools.oauth2
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.