Python runtime customization [sitecustomize, usercustomize]

site is a module that is automatically imported at initialization, and adds site-specific built-in functions. Furthermore, this module realizes the customization function by loading the specified additional module, and site-specific and user-specific customization is possible.

Official documentation

Motivation

I wrote usercustomize, so don't forget that I wrote it.

environment

macOS Catalina Python 3.7

Method

There are two modules loaded by site, site customize and ʻuser customize`. The scope of application is different. The installation location is each site-packages directory. You can check it as follows.

>>> import site
>>> site.getsitepackages()
['/usr/local/var/pyenv/versions/3.7.4/lib/python3.7/site-packages']
>>> site.getusersitepackages()
'/Users/[user_name]/.local/lib/python3.7/site-packages'

python:/User/[user_name]/.local/lib/python3.7/site-packages.py


print('Hi')

Start the interpreter

[user_name]@MacBook ~ % python
Hi
Python 3.7.4 (default, Oct  5 2019, 02:45:54)
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

It is displayed as Hi.

bonus

Perfect Python introduces a hook that uses pdb to automatically start the debugger when an exception is caught. Was there. The debugger starts every time an Exception occurs, so I feel that it is perfect for getting used to pdb.

It became convenient by making a slight improvement so that the start of pdb is ignored when a specified error occurs.

usercutomize.py


import pdb
import sys
import traceback


IGNORE = {'NameError', 'ModuleNotFoundError', 'KeyboardInterrupt', 'SyntaxError'}


def debug_rescue(_type, _value, _traceback):
    traceback.print_exception(_type, _value, _traceback)
    if _value.__class__.__name__ not in IGNORE:
        pdb.pm()


sys.excepthook = debug_rescue

Recommended Posts

Python runtime customization [sitecustomize, usercustomize]
Python SDP runtime comparison
Receive runtime arguments in Python 2.7
Execute Python Script during CodeSys # RunTime