简体   繁体   English

内置的python加载模块

[英]python load module from built-in

I'm using python 3, and i have a module named "http" (mypackage.http) , and i have another module called foo, i want to load the built-in http module (not my mypackage.http module) 我正在使用python 3,并且我有一个名为"http" (mypackage.http)模块,并且我还有一个名为foo的模块,我想加载内置的http module (不是mypackage.http模块)

I can use 我可以用

imp.find_module('http', sys.path[1:])

for get the built-in __ init__.py importlib path 用于获取内置的__ init__.py importlib path

Example: 例:

/usr/local/Cellar/python3/3.3.2/Frameworks/Python.framework/Versions/3.3/lib/python3.3/importlib/__ init__.py

But the use of imp.find_module()/load_module() are deprecated. 但是不建议使用imp.find_module()/ load_module()。

how can i import this built-in http module by another way like importlib ? 如何通过其他类似importlib方式导入此内置http module

project example: 项目实例:

  • mypackage mypackage的
    • _ init _ .py _ init _ .py
    • http.py (has related http classes, etc) http.py(具有相关的http类,等等)
    • foo.py (needs to use built-in http and not the mypackage.http) foo.py(需要使用内置的http而不是mypackage.http)

Thanks! 谢谢!

Just use 只需使用

import http

In Python 2, this wouldn't have worked if foo was in mypackage , but relative imports need to be explicit in Python 3. 在Python 2中,如果foo位于mypackage ,则此方法不起作用,但是相对导入必须在Python 3中是显式的。

If you're running the module as a script, you'll need to fix the path somehow. 如果您将模块作为脚本运行,则需要以某种方式修复路径。 If mypackage is findable using the normal import mechanisms, then you can run the module with the -m switch: 如果可以使用常规导入机制找到mypackage ,则可以使用-m开关运行模块:

python -m mypackage.foo

Otherwise, you may need to check the path and alter it manually, as well as setting __package__ so relative imports work right. 否则,您可能需要检查路径并手动更改它,以及设置__package__以便相对导入正常工作。

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

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