简体   繁体   中英

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. For example imagine you are running python from a directory (top_level) that has the following structure:

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. But after installing you can import cool_mod.sweet_module from anywhere. 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.

Or, use imp.load_source to load a module from specified path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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