8

I want to execute code after the python interpreter has started.

We use virtualenv and up to now we had a file called sitecustomize.py which got executed during interpreter start up.

The sitecustomize.py was part of our project. We use the Django definition of this term: It is a small python module which only holds config and nearly no code: Django's Definition of "Project"

Unfortunately some linux distros (Ubuntu) provide a global sitecustomize, and our per virtualenv sitecustomize does not get loaded.

Question

How to run Python code on interpreter startup in a virtualenv?

This code should be executed even if the interactive interpreter gets started.

Goal vs Strategy

I don't care if this hook is called "sitecustomize" or different :-)

kmaork
  • 5,722
  • 2
  • 23
  • 40
guettli
  • 25,042
  • 81
  • 346
  • 663
  • you can place your code (bash that runs the python script) at the bottom of `bin/activate`....after the virtualenv is activated whatever code you place there would run – danidee Nov 08 '16 at 10:54
  • @danidee AFAIK this does not work if you create a `console_script` via `setup.py`. The python interpreter of the virtualenv gets used, but the `bin/active` script does not get executed. – guettli Nov 08 '16 at 12:59

3 Answers3

7

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!!')

Contents of setup.py:

from setuptools import setup

setup(
    name='pth_startup_example',
    data_files=[
        ('.', ['startup.pth'])
    ]
)

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.

kmaork
  • 5,722
  • 2
  • 23
  • 40
  • It should be noted that in such a `.pth` file, [only lines starting with `import ` are executed](https://docs.python.org/3/library/site.html?highlight=executed). – Seb Mar 14 '23 at 13:21
2

You can use a pth file like explained in this answer:

https://stackoverflow.com/a/52555465/633961

A pth file gets loaded before the interpreter executes the first line of its input.

guettli
  • 25,042
  • 81
  • 346
  • 663
0

Use usercustomize.

On some linux distros a global sitecustomize exists, on some not.

This can lead to confusing behaviour.

No linux distro provides a usercustomize.

See site

... After this, an attempt is made to import a module named usercustomize, which can perform arbitrary user-specific customizations, if ENABLE_USER_SITE is true.

guettli
  • 25,042
  • 81
  • 346
  • 663