[issue45468] Add support for preloading a Python script

Gabriele N Tornetta report at bugs.python.org
Thu Oct 14 07:51:17 EDT 2021


New submission from Gabriele N Tornetta <phoenix1987 at gmail.com>:

I would like to propose adding support for preloading a Python script before executing a Python application.


Potential design:

A new environment variable (e.g. PY_PRELOAD, an allusion to LD_PRELOAD, or PYTHONPRELOAD to be more aligned with the naming pattern of existing variables) is used to specify the path of the script to execute. The script is then executed just before the import of the site module. This is similar to what PYTHONSTARTUP does, except that it works in all cases, not just when launching the REPL.


Rationale:

There are examples of tools that require performing some operations (e.g. monkey-patching) before starting the actual Python application. Currently, this could be achieved in the following rather contrived way:

- prepare an ad-hoc sitecustomize.py file
- add its path to PYTHONPATH
- run the Python application with the computed PYTHONPATH

The ad-hoc sitecustomize.py requires the following steps

- run the custom initialisation code
- remove the path of the custom sitecustomize.py script from sys.path
- unload the sitecustomize module
- try importing sitecustomize to force-load any original sitecustomize scripts that would have run otherwise

The new environment variable makes the whole process a lot easier by allowing tools to just set a single environment variable to achieve the same result.

----------
components: Interpreter Core
messages: 403898
nosy: Gabriele Tornetta
priority: normal
severity: normal
status: open
title: Add support for preloading a Python script
type: enhancement
versions: Python 3.11

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45468>
_______________________________________


More information about the Python-bugs-list mailing list