文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

-- 218.25.66.198 [2004-09-29 06:43:22]

1. 描述

Dynamically Changing the Python Search Path

需要动态改变Python的查找路径

Credit: Robin Parmar

1.1. 问题 Problem

Modules must be on the Python search path before they can be imported, but you don't want a huge permanent path, because that slows things down梱ou want to change the path dynamically.

Python模块在引入前必须在Python的查找路经集合中,但是,一个很大、不变的路径会导致程序变慢。需要动态改变Python查找路径。

1.2. 解决 Solution

We just conditionally add a directory to Python's sys.path, carefully checking to avoid duplication:

可以在一定条件下将一个目录加入到Python的查找路径中,注意不要重复:

   1 
   2 def AddSysPath(new_path):
   3     """ AddSysPath(new_path): adds a directory to Python's sys.path
   4 
   5     Does not add the directory if it does not exist or if it's already on
   6     sys.path. Returns 1 if OK, -1 if new_path does not exist, 0 if it was
   7     already on sys.path.
   8     """
   9     import sys, os
  10 
  11     # Avoid adding nonexistent paths                                   #处理参数目录不存在的情况
  12     if not os.path.exists(new_path): return -1
  13 
  14     # Standardize the path. Windows is case-insensitive, so lowercase  #路径标准化  
  15     # for definiteness.
  16     new_path = os.path.abspath(new_path)
  17     if sys.platform == 'win32':
  18         new_path = new_path.lower(  )
  19 
  20     # Check against all currently available paths                    #检查当前路经
  21     for x in sys.path:
  22         x = os.path.abspath(x)
  23         if sys.platform == 'win32':
  24             x = x.lower(  )
  25         if new_path in (x, x + os.sep):
  26             return 0
  27     sys.path.append(new_path)
  28     return 1
  29 
  30 if _ _name_ _ == '_ _main_ _':
  31     # Test and show usage
  32     import sys
  33 
  34     print 'Before:'
  35     for x in sys.path: print x
  36 
  37     if sys.platform == 'win32':
  38           print AddSysPath('c:\\Temp')
  39           print AddSysPath('c:\\temp')
  40     else:
  41           print AddSysPath('usr/lib/my_modules')
  42 
  43     print 'After:'
  44     for x in sys.path: print x

1.3. 讨论 Discussion

Modules must be on the Python search path before they can be imported, but we don't want to have a huge permanent path, because that would slow down every import performed by every Python script and application. This simple recipe dynamically adds a directory to the path, but only if that directory exists and was not already on sys.path.

Python模块在导入前必须在Python的查找路经集合中,但是,一个很大、不变的路径会导致每个脚本和应用的每次import变慢。 上面脚本可以动态的添加目录到Python查找路径中,条件是目录存在同时未包含在sys.path中。

sys.path is a list, so it's easy to add directories to its end, using sys.path.append. Every import performed after such an append will automatically look in the newly added directory, if it cannot be satisfied from earlier ones.

sys.path是一个list,使用sys.path.append函数, 很容易在它的尾部添加新目录。 添加新目录后的每次查找操作,如果在原查找路径中未找到合适的,就会在新添加的目录中查找。

It's no big problem if sys.path ends up with some duplicates or if some nonexistent directory is accidentally appended to it; Python's import statement is clever enough to shield itself against such issues. However, each time such a problem occurs at import time (from duplicate unsuccessful searches, errors from the operating system that need to be handled gracefully, etc.), there is a price to pay in terms of performance. To avoid the risk of these performance issues, this recipe does a conditional addition to sys.path, never appending any dictionary that doesn't exist or is already in sys.path.

如果Python查找路径中包含了意外添加的重复路径或者不存在的路径,查找操作不会有大问题。Python的import语句处理了这种可能性。 不过,真的有这种情况,那么每次查找(由于不必要的重复查找,以及处理操作系统错误的开销) ,会导致性能的降低。为避免性能上的漏洞,脚本中有条件的添加目录,不会添加不存在的目录或者已经被sys.path包含的目录。

1.4. 参考 See Also

Documentation for the sys module in the Library Reference