Python.Module.site

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

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

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

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 的含义分别是什么呢?

Ref[4]

Demo-1: 查看site.PREFIXES

 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/

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


TODO

Running code at Python startup

Modules and Imports

setuptools

时间: 2024-08-10 01:55:24

Python.Module.site的相关文章

[翻译]Python Module of The Week: Counter

Counter是一个来跟踪加入多少个相同值的容器. 初始化:Counter支持三种形式的初始化.它的构造器可以被一组元素来调用,一个包含键值和计数的字典,或者使用关键字参数字符串名称到计数的映射. import collections print collections.Counter(['a', 'b', 'c', 'a', 'b', 'b']) print collections.Counter({'a':2, 'b':3, 'c':1}) print collections.Counter

python module, package

任何Python程序都可以作为模块导入:在导入自己的模块时,需要添加路径: import sys sys.path.append('absolute-path'); (__pycache__是执行main.py时创建的) hello.py内容: def sayHello(): print('hello,world') main.py内容 import sys sys.path.append("/home/icode0410/Documents/code/python/module/modules

Nuke Python module的使用

最近很多脚本工作都需要脱离nuke的gui环境运行,没有了script editor就必须要尝试Nuke Python module功能了.该模式可以执行大部分在GUI环境中的命令,在自动生成或者批量处理nuke工程时非常高效. 下面简单介绍该模式: 从8.0版本开始Nuke就可以被当作一个python模块来使用了. 这意味着你现在可以在VFX流程中使用Python来做很多复杂的事,对于大部分的2DPython模块,3DPython模块以及视频编辑Python模块,这是一个易用的,产品级的,不可

在IDL中调用自定义Python Module

在IDL中调用自定义PythonModule 要在IDL8.3中调用自定义的Python Module以实现在IDL中不方便完成的任务.如使用一些开发包,但是这个开发包并不支持IDL,毕竟使用IDL的人数还是相对较少的.因此,混合编程是一个解决之道.下面介绍在IDL(32位,下面的介绍都只是针对32位的IDL8.3)中调用自定义的PythonModule的操作步骤. 1)  下载Slither(The IDL toPython Bridge).下载地址http://research.jacque

Python module中的全局变量

Python module中的全局变量 我想要实现一个python module,这个module中有一些配置项,这些配置项可以被读取,被修改.一个可行的方案是把这些配置项写到一个叫settings.py的文件中. 现在我有一个叫zz的module,它的文件结构是这样的: __init__.py __all__=['sleep', 'wake', 'settings'] from sleep import fall_asleep from wake import wake_up settings

python module的结构

python有很多module,下面是module的结构图: 拿httplib做例子,httlip module有: 4个class( HTTPConnection,HTTPSConnection,HTTPResponse,HTTPMessage ), 12个exception( HTTPException,NotConnected,InvalidURL,UnknownProtocol,UnknownTransferEncoding,UnimplementedFileMode,Incomplet

Python Module和Package辨析

Python 基础学习 说明 这不是最基础的新手教程,如需了解Python的数据类型.变量等基础内容,请移步:https://docs.python.org/2/tutorial/index.html 这里的代码使用Python2.7环境,没有在>3版本号环境下測试,如有不兼容等问题,欢迎交流.邮箱:[email protected] 模块(Moudule)和包(Package)辨析 module 通常模块为一个文件,直接使用import来导入就好了.能够作为module的文件类型有".p

windows下pip安装python module失败

C:\Python27\pywin32-214>setup.py -q install Building pywin32 2.7.214.0 Traceback (most recent call last): File "C:\Python27\pywin32-214\setup.py", line 2152, in <module> ('', ('pywin32.pth',)), File "C:\Python27\lib\distutils\core.

Python module

1. module name fibo.__name__ # file fibo.py def f(x): return x*x import fibo fibo.f(10) # module name then function name fl = fibo.f # to make it call like locally from fibo import f from fibo import * # import all except  for name start with '_' 2.