Python Has a Startup File!

Ryan Palo - Jul 4 '18 - - Dev Community

Cover Photo by Uriel Soberanes on Unsplash

So, I want to be clear. I knew that Python has a startup customization file this whole time I've been using Python. I didn't just find out about it this week. I mean, of course Python has a startup file. Everything has a startup file! I just want to make sure you know about it. (Only joking, I had no idea this was a thing.)

Before you bring it up, I already know about bPython, the awesome, syntax-highlighty, tab-completey, auto-indenty, wonderful drop in replacement for the regular Python interpreter. I use it all the time. But that's not what this blog post is about. P.S. if you didn't know about bPython, I highly recommend it (Windows users' mileage may vary).

$PYTHONSTARTUP

If you have the environment variable $PYTHONSTARTUP set to a valid Python file, that file will get run when starting up the Python interpreter.

$ export PYTHONSTARTUP="~/.config/pythonrc.py"
Enter fullscreen mode Exit fullscreen mode

Don't worry about the name of the file. Name it whatever you want! python_startup.py, or just pythonrc. You can also put it in whatever directory you want. Just make sure your $PYTHONSTARTUP environment variable matches. Then, you can put anything you want into that file.

# ~/.config/pythonrc.py
a = "Wahoo!"
print("Soup")
try:
    import numpy as np
except ImportError:
    print("Could not import numpy.")
Enter fullscreen mode Exit fullscreen mode

Try running your Python interpreter.

$ python  # or python3
Enter fullscreen mode Exit fullscreen mode

And you should see something similar to the following:

Python 3.7.0 (default, Jun 29 2018, 20:14:27)
[Clang 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Soup
>>> np
<module 'numpy' from '/usr/local/lib/python3.7/site-packages/numpy/__init__.py'>
>>> np.zeros((3, 2))
array([[0., 0.],
       [0., 0.],
       [0., 0.]])
>>> a
'Wahoo!'
Enter fullscreen mode Exit fullscreen mode

You can import commonly used libraries, create variables for yourself, and more.

sys.ps1 and sys.ps2

One neat thing to do is to set the sys.ps1 and sys.ps2 variables, which control your Python prompts.

# ~/.config/pythonrc.py

import sys

sys.ps1 = "šŸŒ®"
sys.ps2 = "šŸ’©"

# ...
Enter fullscreen mode Exit fullscreen mode

And, back in the interactive REPL:

šŸŒ® for i in range(10):
šŸ’©     print("I am a mature adult.")
šŸ’©
I am a mature adult.
I am a mature adult.
...
Enter fullscreen mode Exit fullscreen mode

In fact, you can even set sys.ps1 and sys.ps2 to objects that aren't even strings! If they're not strings, Python will call str(obj) on them.

# ~/.config/pythonrc.py

import sys
from datetime import datetime

class CustomPS1:
    def __init__(self):
        self.count = 0

    def __str__(self):
        self.count += 1
        return f"({self.count}) {datetime.now().strftime('%H:%m %p')} > "

sys.ps1 = CustomPS1()
Enter fullscreen mode Exit fullscreen mode

And in the interpreter:

(1) 10:06 AM > for i in range(10):
...     print("Am I cool now?")
...
Am I cool now?
Am I cool now?
# ...
(2) 11:06 AM >
Enter fullscreen mode Exit fullscreen mode

The -i Flag

In addition to these new superpowers, you can temporarily make any Python script your startup script. This could come in really handy for some interactive debugging. Let's say you're working on a project and you have a script that defines some functions:

# cool_script.py

def what_time_is_it():
    return "Party Time"
Enter fullscreen mode Exit fullscreen mode

You can use the -i flag when you run the Python interpreter to use cool_script.py as your startup file instead of your usual one.

$ python -i cool_script.py
>>> what_time_is_it()
'Party Time'
Enter fullscreen mode Exit fullscreen mode

If you do some cool things with your startup file, share it with me! I want to know about it! Happy coding!

Originally posted on assert_not magic?

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .