7

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?

3
  • Might be using a sledghammer here, but make a symlink to your python executable that runs that command first then the needed file from the cli arg after python? You could name it something different, also. Commented Jan 9, 2013 at 18:47
  • If you've run into this problem you would likely be interested in ipython ipython.org. Commented Jan 9, 2013 at 18:47
  • are you using the shell to practice or something? Commented Jan 9, 2013 at 18:48

5 Answers 5

14

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
>>> 
Sign up to request clarification or add additional context in comments.

3 Comments

I see what you're going for here, but your formatting is pretty strange. You might want to work on that to make it a bit more clear what you're actually doing... In other words, highlight that the important part is python -i script.py.
@mgilson Does this look better?
that's about a million times better. I like it now :). +1
9

I think you're looking for the PYTHONSTARTUP environment variable

Comments

2

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

Comments

2

Create a file called usercustomize.py, and place it in your USER_SITE directory (which you can find as import site; site._script(). This file will be executed every time you start an interpreter.

There's a similar file called sitecustomize.py which is executed anytime anyone starts Python.

Comments

0

This is a Windows solution, but I'm sure a Unix equivalent could be done. I created a file \MyPythonCode\autoexec.py (the last line of which is a print("Autoexec Complete")) and a BAT file MyPython.Bat which has:

cd \myPythonCode
python -i autoexec.py

I just use the command: mypython

to start the Python environment every time, now.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.