简体   繁体   中英

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?

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.

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

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM