How to Run a Script when Python Shell Starts up?

What's the use of the PYTHONSTARTUP variable?

ยท

2 min read

In the previous post, we explored various ways to clear the Python shell.

tl;dr

import os
os.system("clear") # Linux/Mac
os.system("CLS")  #  For windows

We have also discussed how running a 2 line program every time you want to clear the screen isn't optimal.

An optimal solution would be to write this in a script and have it ready every time a Python IDLE starts.

Write the script

Let's create the script we want to run with PYTHONSTARTUP. Create a Python file, let's say startup.py. I'm creating a function clear, which one can call at any point to clear the idle screen.

# startup.py

import os
def clear():
    x = os.system("clear") # assigning to x to avoid printing output on screen

Interactive shell

A simple way initiates the above script on the Python shell is by using the `-i' option.

python -i startup.py

The downside of this method is

  • You have to be mindful to use the script every time
  • Typing more, which we are trying to avoid in the first place
  • The startup script might be far from your current directory. You must remember the path and mention it again in more characters.

PYTHONSTARTUP Variable

PYTHONSTARTUP is one of the Python command-line environment variables which can be used to manipulate how Python behaves. In our case, this is loading a script on shell startup.

It's super simple. Add the following snippet to your ~/.bashrc or a file associated with your shell. Ensure the startup.py is in the same directory as the RC file.

export PYTHONSTARTUP=startup.py

That's it. Irrespective of where you start the python shell(even virtualenvs), you will have a clear function already loaded and ready to be called to clear your IDLE.


Does the idea of linking a script trigger any cool ideas for you? Comment below

ย