如何在Virtualenv中的解释器启动上执行Python代码?

gue*_*tli 4 python django virtualenv

我想在python解释器启动后执行代码。

我们使用virtualenv,到目前为止,我们有一个名为sitecustomize.py的文件,该文件在解释器启动期间执行。

sitecustomize.py是我们项目的一部分。我们使用该术语的Django定义:这是一个小型python模块,仅包含配置,几乎没有代码:Django的“ Project”定义

不幸的是,一些Linux发行版(Ubuntu)提供了一个全局sitecustomize,而我们的每个virtualenv sitecustomize均未加载。

如何在virtualenv中的解释器启动时运行Python代码?

即使交互式解释器启动,也应执行此代码。

目标与策略

我不在乎此挂钩是否称为“ sitecustomize”或其他:-)

kma*_*ork 5

An addition to @guettli's answer: you can even make a .pth file a part of your package's distribution, so when it is installed it will make some code run on python startup, and when it is uninstalled, this code will no longer run.

Example package:

  • startup.pth
  • setup.py

Contents of startup.pth:

import sys; print('Success!!')
Run Code Online (Sandbox Code Playgroud)

Contents of setup.py:

from setuptools import setup

setup(
    name='pth_startup_example',
    data_files=[
        ('.', ['startup.pth'])
    ]
)
Run Code Online (Sandbox Code Playgroud)

After creating these files, run pip install . in the same directory with the files. That should install startup.pth in your root python directory, and you should see Success!! printed every time your interpreter runs. To undo that, run pip uninstall pth_startup_example.

You can add this to an existing package, or make a package like this a dependency of a different package.