简体   繁体   中英

python pth file import statements ineffective?

The import statements executed from the pth files seem to execute fine. But I don't seem to be able to access any of the modules that are imported in this way.

What is this sorcery?

From your comments I'm guessing that you're getting NameError exceptions for some modules due to confusion about the purpose of .pth -files.

pth stands for path . The purpose is to add paths to sys.path (pythonpath - path that Python uses to find modules during import). See site module documentation .

The lines that start with import can contain any code but generally they modify sys.path . For example, setuptools machinery:

import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sys.path[p:p]=new; sys.__egginsert = p+len(new)

Another common case is when .pth -files are used to implement "namespace" packages :

import sys,types,os; p = os.path.join(sys._getframe(1).f_locals['sitedir'], *('zope',)); ie = os.path.exists(os.path.join(p,'__init__.py')); m = not ie and sys.modules.setdefault('zope',types.ModuleType('zope')); mp = (m or []) and m.__dict__.setdefault('__path__',[]); (p not in mp) and mp.append(p)

.pth -files are not there to make module names appear in your code. To import some_module , add at the top of each module where you want to use it:

import some_module

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