简体   繁体   English

本地vs全球导入python

[英]Local vs Global imports python

I am not seeing an answer to this out there, so apologies if this is a duplicate. 我没有看到这方面的答案,所以如果这是重复的道歉。 Basically, I am trying to understand how to force my interpreter (2.7) to import a module from site packages if there is a conflict. 基本上,我试图了解如果存在冲突,如何强制我的解释器(2.7)从站点包导入模块。 For example imagine you are running python from a directory (top_level) that has the following structure: 例如,假设您从具有以下结构的目录(top_level)运行python:

top_level
----cool_mod
    ----init.py
    ----sweet_module.py

but you have already installed sweet module to site packages. 但是您已经将甜蜜模块安装到站点包中。 When in this directory (but no others) if you run: 如果您运行在此目录中(但没有其他目录):

from cool_mod.sweet_module import *

you will import from the local module, not the global one. 您将从本地模块导入,而不是从全局模块导入。 Can I change this somehow? 我能以某种方式改变它吗?

This situation might arise from the case: 这种情况可能来自案件:

top_level

setup.py
----cool_mod
    ----init.py
    ----sweet_module.py

You can run cool_mod.sweet_module before installing if you working directory is top_level. 如果您的工作目录是top_level,则可以在安装之前运行cool_mod.sweet_module。 But after installing you can import cool_mod.sweet_module from anywhere. 但安装完成后,您可以从任何地方导入cool_mod.sweet_module。 However, if you ever import from this directory, even after installation, you still import the local copy 但是,如果您从此目录导入,即使在安装后,仍然会导入本地副本

Inserting the site package directory at the begining of sys.path, and then import. 在sys.path的开头插入站点包目录,然后导入。

Or, use imp.load_source to load a module from specified path. 或者,使用imp.load_source从指定路径加载模块。

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

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