site

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

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

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

1. Import Path

import path 参考Ref[5]。

在解释器(interpreter)启动时,site会被自动的导入(imported)。在导入时,site扩展sys.path。

扩展的方式是使用sys.prefix 和 sys.exec_prefix。site.py中PREFIXES的定义如下,Ref[3]:

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

Q: 那么sys.prefix sys.exec_prefix 和 sys.path 的含义分别是什么呢?

Ref[4]

Demo-1: 查看site.PREFIXES

 import sys
import os
import platform
import site if 'Windows' in platform.platform():
SUFFIXES = [
'',
'lib/site-packages',
]
else:
SUFFIXES = [
'lib/python%s/site-packages' % sys.version[:3],
'lib/site-python',
] print 'Path prefixes:'
for p in site.PREFIXES:
print ' ', p for prefix in sorted(set(site.PREFIXES)):
print
for suffix in SUFFIXES:
path = os.path.join(prefix, suffix).rstrip(os.sep)
print path
print ' exists:', os.path.exists(path)
print ' in path:', path in sys.path

2. User Directories (用户目录)

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

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

 import site

 print 'Base:', site.USER_BASE
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的内容是:  

 # Add a single subdirectory to the path.
./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 如下:

 print 'Loading sitecustomize.py'

 import site
import platform
import os
import sys path = os.path.join('/opt', 'python', sys.version[:3], platform.platform())
print 'Adding new path', path site.addsitedir(path)

创建 site_sitecustomize.py 如下:

 import sys

 print 'Running main program'

 print 'End of path:', sys.path[-1]

将脚本 sitecustomize.py 和 site_sitecustomize.py 都放在with_sitecustomize目录中:

with_sitecustomize/

  |--sitecustomize.py

  |--site_sitecustomize.py

然后执行如下命令:

 $ PYTHONPATH=with_sitecustomize python with_sitecustomize/site_sitecustomize.py

输出如下:

Loading sitecustomize.py
Adding new path /opt/python/2.7/Darwin-13.4.-x86_64-i386-64bit
Running main program
End of path: /opt/python/2.7/Darwin-13.4.-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

Python.Module.site的更多相关文章

  1. install python module

    [install python module] 参考:http://docs.python.org/2.7/install/index.html

  2. Nuke Python module的使用

    最近很多脚本工作都需要脱离nuke的gui环境运行,没有了script editor就必须要尝试Nuke Python module功能了.该模式可以执行大部分在GUI环境中的命令,在自动生成或者批量 ...

  3. __import__ 与动态加载 python module

    原文出处: koala bear    Direct use of __import__() is rare, except in cases where you want to import a m ...

  4. Python module中的全局变量

    Python module中的全局变量 我想要实现一个python module,这个module中有一些配置项,这些配置项可以被读取,被修改.一个可行的方案是把这些配置项写到一个叫settings. ...

  5. Python module all in one

    Python module all in one Python Modules https://docs.python.org/3/tutorial/modules.html Fibonacc # F ...

  6. import 本地Python module或package

    很基础很重要的一课,虽然很简单,但是防止以后忘了,还是记下来 这个笔记里说的都是import本地的,自己创建的,或者复制粘贴的别人的,总之“不是安装到library”的module or packag ...

  7. python module的结构

    python有很多module,下面是module的结构图: 拿httplib做例子,httlip module有: 4个class( HTTPConnection,HTTPSConnection,H ...

  8. Python : Module

    在Python中,一个.py文件代表一个Module.在Module中可以是任何的符合Python文件格式的Python脚本.了解Module导入机制大有用处. 1 Module 组成 1.1 Mod ...

  9. python module install

    1.issue: How can I bypass kivy module error: ImportError: DLL load failed: The specified module coul ...

随机推荐

  1. java使用jsch连接linux

    由于项目需要使用java来linux进行管理,近一番查找,发现第三方jar包 jsch 可以轻松实现对linux的管理,(相关文档及例子请访问官网www.jcraft.com),故引进. 在网上搜索了 ...

  2. js类式继承模式学习心得

    最近在学习<JavaScript模式>,感觉里面的5种继承模式写的很好,值得和大家分享. 类式继承模式#1--原型继承 方法 让子函数的原型来继承父函数实例出来的对象 <script ...

  3. Java三大框架的配置

    1. 首先是spring,右键项目-myeclipse-capabilitise-install spring etc.类似的就好,生成applicationContext.xml和spring一些类 ...

  4. Theme皮肤文件(json解析、多文件管理)

    一  官方教程 http://developer.egret.com/cn/github/egret-docs/extension/EUI/skin/theme/index.html 二 thm主题文 ...

  5. JPA merge(obj) 方法

    JPA中的merge类似Hibernate中的saveOrUpdate方法,当数据库中存在id=2的Person,在em.close()时会发送一条update语句,而当数据库中不存在id=2的Per ...

  6. zookeeper dubbo 问题解决录

    问题1: 运行起来不报错,不过在Console没有zookeeper的心跳信息,也就是说没有配置上zookeeper,而出错的原因是下面蓝色这段解析不了 spring-dubbo-provider.x ...

  7. MVC项目

    MVC 项目分析: 1.AssemblyInfo.cs  保存管理文件发布的一些属性和版本号 2.Content文件夹(保存相关的样式文件.CSS),scripts文件夹(保存相关的),fonts文件 ...

  8. show status和show variables区别解析

    1.show status    查看系统运行的实时状态,便于dba查看mysql当前运行的状态,做出相应优化,动态的,不可认为修改,只能系统自动update. MariaDB [(none)]> ...

  9. linux一些目录功能

    (1)/etc     ----存放配置文件和子目录 (2)/dev     -----是linux的外设文件,dev是devxe(设备)的缩写,在这个目录下存放的是所有linux的外设文件,.在li ...

  10. MVC数据传递和多表单

    1.数据传递(1)session和TempData 全局变量,可以将值从一个动作传递到另一个动作,也可以从控制层传递到视图层. TempData取一遍值后自动销毁. session使用: //控制器中 ...