Brad P.
Brad P.

Reputation: 308

How can I run Python commands every time I start Python

I would like to know how I can have a command, or several commands, run at startup every time I start a python interpreter.

Is there a way to accomplish this in python, like a .bashrc or .profile file does for linux/unix?

Upvotes: 2

Views: 452

Answers (1)

Brad P.
Brad P.

Reputation: 308

You can set an environment variable PYTHONSTARTUP to point at a file containing the commands you wish to run at the startup of all python interpreters.

More info can be found in the python docs: https://docs.python.org/2/tutorial/interpreter.html#the-interactive-startup-file

There is also this useful bit of information if you want to run either an additional startup file from the current directory or run this global startup file from a script:

If you want to read an additional start-up file from the current directory, you can program this in the global start-up file using code like if os.path.isfile('.pythonrc.py'): execfile('.pythonrc.py'). If you want to use the startup file in a script, you must do this explicitly in the script:

import os
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
    execfile(filename)

Upvotes: 3

Related Questions