Python.Module.site

site

" This module is automatically imported during initialization. The automatic importcss

can be suppressed using the interpreter’s -S option.html

Importing this module will append site-specific paths to the module search path and add a few builtins. " Ref[1]python

1. Import Path 

import path 參考Ref[5]。git

在解釋器(interpreter)啓動時,site會被自動的導入(imported)。在導入時,site擴展sys.path。github

擴展的方式是使用sys.prefix 和 sys.exec_prefix。site.py中PREFIXES的定義以下,Ref[3]:shell

1 # Prefixes for site-packages; add additional prefixes like /usr/local here
2 PREFIXES = [sys.prefix, sys.exec_prefix]

 

Q: 那麼sys.prefix sys.exec_prefix 和 sys.path 的含義分別是什麼呢? app

Ref[4]python2.7

Demo-1: 查看site.PREFIXESide

 1 import sys
 2 import os
 3 import platform
 4 import site
 5 
 6 if 'Windows' in platform.platform():
 7     SUFFIXES = [
 8         '',
 9         'lib/site-packages',
10         ]
11 else:
12     SUFFIXES = [
13         'lib/python%s/site-packages' % sys.version[:3],
14         'lib/site-python',
15         ]
16 
17 print 'Path prefixes:'
18 for p in site.PREFIXES:
19     print '  ', p
20 
21 for prefix in sorted(set(site.PREFIXES)):
22     print
23     for suffix in SUFFIXES:
24         path = os.path.join(prefix, suffix).rstrip(os.sep)
25         print path
26         print '   exists:', os.path.exists(path)
27         print '  in path:', path in sys.path

 

2. User Directories (用戶目錄)

http://pymotw.com/2/site/ui

2.1 USER_BASE 和 USER_SITE

"In addition to the global site-packages paths, site is responsible for adding the

user-specific locations to the import path." Ref[2]

Q: globale site-package 和 import path分別是什麼? 

user-specific path是基於USER_BASE的。在USER_BASE中的是site-packages directory,該directory的路徑是

USER_SITE

"The user-specific paths are all based on the USER_BASE directory, which usually

located in a part of the filesystem owned (and writable) by the current user."

A):

Demo-2: 查看 USER_BASE USER_SITE

1 import site
2 
3 print 'Base:', site.USER_BASE
4 print 'Site:', site.USER_SITE

 

輸出是:

"

Base: /Users/XiaoKL/Library/Python/2.7

Site: /Users/XiaoKL/Library/Python/2.7/lib/python/site-packages

"

USER_BASE能夠由環境變量PYTHONUSERBASE來設置。

B): 命令查看USER_BASE USER_SITE:

$ python -m site --user-base

$ python -m site --user-site

$ PYTHONUSERBASE=/tmp/$USER python -m site --user-base

$ PYTHONUSERBASE=/tmp/$USER python -m site --user-site

 

python的-m module-name:

       "-m module-name

              Searches  sys.path for the named module and runs the correspond-

              ing .py file as a script. " Ref[man python2.7]

 

 

2.2 Disable user directory

The user directory can also be explicitly disabled on the command line with -s.

$ python -s site_enable_user_site.py

 

3. Path Configuration Files (路徑配置文件)

在路徑被添加到import path的過程當中,path configuration file被掃描解析。

A path configuration file is a plain text file with the extension .pth

每一行能夠是:

  1. A full or relative path to another location that should be added to the import path.
  2. A Python statement to be executed. All such lines must begin with an import statement.
  3. Blank lines are ignored.
  4. A line starting with # is treated as a comment and ignored.

路徑配置文件的做用:

"Path configuration files can be used to extend the import path to look in locations that

would not have been added automatically. "  Ref[2]

Demo-3: 沒有使用路徑配置文件的Case

建立一個目錄with_modules。

$(ROOT_DIR)

|-- site_addsitedir.py

|--with_modules 

    |--mymodule.py 

site_addsitedir.py: site_addsitedir.py

mymodule.py: mymodule.py

 

$ python site_addsitedir.py  with_modules

 

"If the directory given to addsitedir() includes any files matching the pattern *.pth,

they are loaded as path configuration files." Ref[2]

Demo-4: 使用路徑配置文件的Case

$(ROOT_DIR)

|-- site_addsitedir.py

|--with_modules 

    |--pymotw.pth

    |--subdir

        |--mymodule.py

 

pymotw.pth的內容是:  

1 # Add a single subdirectory to the path.
2 ./subdir

 

運行 "$ python site_addsitedir.py  with_modules" 的輸出以下:

__file__: site_addsitedir.py
cwd: /Users/XiaoKL/Projects/PrivateProject/PythonProject/site
basename: site_addsitedir.py
abspath: /Users/XiaoKL/Projects/PrivateProject/PythonProject/site/site_addsitedir.py
script_directory: /Users/XiaoKL/Projects/PrivateProject/PythonProject/site
module_directory: with_modules
Could not import mymodule: No module named mymodule
------------
New paths:
   /Users/XiaoKL/Projects/PrivateProject/PythonProject/site/with_modules
   /Users/XiaoKL/Projects/PrivateProject/PythonProject/site/with_modules/subdir
-------------
Loaded mymodule from with_modules/subdir/mymodule.py

 

4. sitecustomize

"The site module is also responsible for loading site-wide customization defined by the local

site owner in a sitecustomize module.

Uses for sitecustomize include extending the import path and enabling coverage, profiling, or

other development tools."  Ref[2]

Demo-5: sitecustomize的使用

建立 sitecustomize.py 以下:

 1 print 'Loading sitecustomize.py'
 2 
 3 import site
 4 import platform
 5 import os
 6 import sys
 7 
 8 path = os.path.join('/opt', 'python', sys.version[:3], platform.platform())
 9 print 'Adding new path', path
10                     
11 site.addsitedir(path)

 

建立 site_sitecustomize.py 以下:

1 import sys
2 
3 print 'Running main program'
4 
5 print 'End of path:', sys.path[-1]

 

將腳本 sitecustomize.py 和 site_sitecustomize.py 都放在with_sitecustomize目錄中:

with_sitecustomize/

  |--sitecustomize.py

  |--site_sitecustomize.py

而後執行以下命令:

1 $ PYTHONPATH=with_sitecustomize python with_sitecustomize/site_sitecustomize.py

 

輸出以下:

Loading sitecustomize.py
Adding new path /opt/python/2.7/Darwin-13.4.0-x86_64-i386-64bit
Running main program
End of path: /opt/python/2.7/Darwin-13.4.0-x86_64-i386-64bit

  

"Since sitecustomize.py is meant for system-wide configuration, it should be installed somewere

in the default path (usally in the site-packages directory). This example sets PYTHONPATH explicitly

to ensure the module is picked up."  Ref[2]

Q: PYTHONPATH 是個什麼東西? 

"The import search path list can be modified before starting the interpreter by setting

the shell variable PYTHONPATH to a colon-separated list of directories."

 

5. usercustomize 

"Similar to sitecustomize, the usercustomize module can be used to set up user-specific settings

each time the interpreter starts up. usercustomize is loaded after sitecustomize, so site-wide

customizations can be overridden."  Ref[2]

"When the user site directory feature is disabled, usercustomize is not imported" Ref[2]

 

6. Disabling site

-S: Disable the import of the module  site  and  the  site-dependent  manipulations  of sys.path that it entails.

$ python -S site_import_path.py

 

 


Reference

1. site — Site-specific configuration hook

https://docs.python.org/2/library/site.html

2. site

http://pymotw.com/2/site/

3. site.py source code

https://hg.python.org/cpython/file/2.7/Lib/site.py

4. sys-prefix  & sys-exec_prefix

http://pymotw.com/2/sys/interpreter.html#sys-prefix

5. import path

https://pymotw.com/2/sys/imports.html#import-path 


TODO

Running code at Python startup

Modules and Imports

setuptools

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息