Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I start the python shell and automatically initialize it with some commands?

Tags:

python

I find that when I start the python shell I have a bunch of commands I always type to get into the state I want. It is tiresome to keep re-typing these commands, so I have bundled them into a script. Now I just type:

execfile('script.py')

as soon as I enter the shell, and it goes through all the steps to get me to the state I need to be in.

Now I'd like to take it one step further. How can I get the python shell to automatically run script.py every time I start the shell, so I don't have to keep re-typing even that one line?

like image 667
tadasajon Avatar asked Jan 09 '13 18:01

tadasajon


3 Answers

Here's a way without having to mess with environment variables:

For example, if I had a script with the following in it called script.py:

#!/usr/bin/env python
print("example")

I could tell python to run this before bringing me to the interpreter with the -i flag.

$ python -i script.py
example
>>> 
like image 128
Fredrick Brennan Avatar answered Oct 12 '22 14:10

Fredrick Brennan


I think you're looking for the PYTHONSTARTUP environment variable

like image 33
mgilson Avatar answered Oct 12 '22 16:10

mgilson


I'd suggest you to use IPython, if possible. It gives tones of great features, and autoexec is only one of them. But of course, correct answer is mentioned by @mgilston

like image 22
cleg Avatar answered Oct 12 '22 16:10

cleg