J-bob
J-bob

Reputation: 9116

A PYTHONSTARTUP file for a specific directory

I've heard about the PYTHONSTARTUP file as a way to automatically load specified modules and other code when starting python. But PYTHONSTARTUP is a global thing, for all instances of python. Is there such a thing as PYTHONSTARTUP that I can place in a specific directory and runs only when I start python in that directory?

Upvotes: 2

Views: 3393

Answers (4)

Marcin
Marcin

Reputation: 49846

This sounds like you want to use virtualenv. It's a tool for creating isolated python environments with hooks for individual settings. Just put them in the bin/activate of your virtualenv.

Upvotes: 1

mirk
mirk

Reputation: 5520

You can add some code in the python startup-file, which only executes depending on your current working directory.

Adding the snippet below in .python prints hello if python is started from /home/myuser/mydir.

import os

if os.getcwd()=="/home/myuser/mydir":
     print "hello"

Upvotes: 1

tripleee
tripleee

Reputation: 189487

As PYTHONSTARTUP is an environment variable, you can set it on a per-instance basis.

In sh-compatible shells, you can set a variable for the duration of a single process with

PYTHONSTARTUP=/home/you/special.py python arguments ...

To set it permanently for all Python instances, put something like

PYTHONSTARTUP=/home/you/regular.py
export PYTHONSTARTUP

in your shell's startup file.

You can override the global default for the current shell:

bash$ PYTHONSTARTUP=/home/you/another.py

(and export PYTHONSTARTUP if it's not already exported) or for individual processes as per the first example.

On Windows and in Csh-compatible shells, the details of the syntax will be different, but the concept is by and large the same.

Upvotes: 1

Josh Smeaton
Josh Smeaton

Reputation: 48730

Just export the PYTHONSTARTUP environment variable before starting up each project.

export PYTHONSTARTUP=$HOME/myproject/.pystartup
python ~/myproject/start.py

export PYTHONSTARTUP=$HOME/myotherproject/.pystartup
python ~/myotherproject/start.py

Or you could have a simple bash file that contains the environment and the python command you wish to run.

#!/bin/sh
# filename: workon.sh
export PYTHONSTARTUP=$HOME/myproject/.pystartup
python ~/myproject/start.py

Then:

./workon.sh

Upvotes: 2

Related Questions