What is The Python Equivalent of ~/.bashrc?

The Python Equivalent Of Bashrc

Have you ever wondered if Python has something similar to the ~/.bashrc file that Bash uses? Well, wonder no more! In this comprehensive guide, we will explore the various options available in Python to replicate the functionality of ~/.bashrc and customize the Python environment to your liking.

Whether you want to set common environment variables, define reusable functions, or ensure some code runs every time you start Python, this guide covers you. So let’s get started!

Python offers the ability to customize startup behavior similar to ~/.bashrc using the PYTHONSTARTUP environment variable. By pointing this to a Python script containing arbitrary code, you can set common environment variables, define reusable functions and aliases, tweak REPL preferences, automatically load libraries etc. Much like ~/.bashrc for Bash shells!

Also read: [Fix] gcc – fatal error: Python.h: No such file or directory

What does ~/.bashrc do?

For those unfamiliar, ~/.bashrc is a Bash shell script that runs whenever a new terminal session starts in Linux and other Unix-based systems.

It allows users to set custom environment variables, define shell functions, tweak their command prompt – and customize their shell environment however they want.

This user-specific script runs automatically without having to source it every time manually. Pretty nifty!

Some common uses of ~/.bashrc include:

  • Setting the PATH variable to add custom bin directories
  • Defining shorthand shell functions for commonly used commands
  • Setting terminal preferences like colors, prompt format etc.
  • Aliasing long commands to short nicknames
  • Loading libraries that provide useful shell functions

And much more! No wonder it is so popular with Linux power users and system administrators.

But what if you want functionality similar to Python? Read on to find out!

The PYTHONSTARTUP File – ~/.bashrc equivalent for Python

The closest thing Python has to offer compared to ~/.bashrc is the PYTHONSTARTUP environment variable.

You can set this variable to a Python script containing arbitrary code you want to execute every time you start a Python interpreter session.

Here is an example to demonstrate its usage:

# Contents of ~/.pythonstartup file
import sys

print('Python %s on %s' % (sys.version, sys.platform))

def hello():
    print("Hello World!")

# Set ENV var to point to this startup script    
export PYTHONSTARTUP=~/.pythonstartup

Now when you start Python from the terminal, you’ll see:

Python 3.8.2 (default, Apr 27 2020, 15:53:34) 
[GCC 9.3.0] on linux
>>> hello()
Hello World!

The .pythonstartup script runs automatically and defines a reusable hello() function for us!

Some key points to note:

  • The PYTHONSTARTUP file can contain any valid Python code
  • It runs before handing control to the interactive interpreter
  • Functions and variables defined are available in the interactive namespace
  • It runs every time you start Python REPL or execute Python scripts (with caveats, see below)

So this mechanism allows you to customize the Python environment to your liking just like ~/.bashrc!

Differences Between PYTHONSTARTUP and ~/.bashrc

However, there are some subtle differences in Python’s implementation:

  1. No Separate File for Python Scripts: The PYTHONSTARTUP script runs unconditionally whenever you start any Python process – both interactive shells AND Python programs. There is no separate file like ~/.pythonrc that only runs for REPL sessions. While convenient, this could cause namespace pollution for your scripts.
  2. No Automatic Sourcing for Imported Modules: Modules that you import do not automatically source PYTHONSTARTUP. This can lead to confusion if you expect some code to run on all imports.
  3. No Python Version-Specific Files: Unlike Bash, there is no separate startup file for different Python versions. The same PYTHONSTARTUP runs for Python 2.x and Python 3.x interpreters. So you have to handle version differences within the same script using conditional logic.
  4. Overrides Site Customization: Any site-wide customization configured via site.USER_SITE or usercustomize module is overridden by PYTHONSTARTUP if set.

So in summary, while PYTHONSTARTUP provides similar functionality as ~/.bashrc, there are some subtle behavioral differences to keep in mind.

Common Uses for PYTHONSTARTUP

Now that you understand how PYTHONSTARTUP works, what are some common use cases for it?

Here are some ideas to customize your Python environment:

1. Define Convenience Functions and Aliases

You can define reusable helper functions, aliases for common operations, etc. and use it interactively without having to redefine every time:

# ~/.pythonstartup
import os, sys

def ll():
    return os.listdir(os.curdir)

alias = lambda x: os.system(x) 

Now you have shorthand ll to list directory contents and alias to easily invoke shell commands right from Python!

2. Set Custom Environment Variables

Need to pass some config values to your scripts? Set them in PYTHONSTARTUP once and forget about it!

import os
os.environ['API_TOKEN'] = 'secret123' 
os.environ['DB_NAME'] = 'myappdb'

This automatically sets environment variables available to all your Python code.

3. Customize REPL Behavior

Tweak the Python REPL to suit your preferences:

import sys
sys.ps1 = "[custom]> "       # Primary prompt
sys.ps2 = "... "             # Continuation prompt

You can configure prompt format, color scheme, input history etc.

4. Load Helper Libraries and Extensions

Prime your Python environment with useful code and tools by default:

import numpy as np         # Import numpy by default
import custom_utils as cu  # Custom modules

%load_ext line_profiler    # IPython extensions  

This eliminates repetitive import statements and gives you access to extra functionality whenever you interact with Python. As you can see, the use cases are endless! PYTHONSTARTUP lets you customize Python to suit your unique needs and preferences.

Also read: How to Clear the PyCharm Run Window in Python?

Alternative Options

While PYTHONSTARTUP is the most straightforward way to replicate ~/.bashrc functionality, there are a couple of other options:

1. The usercustomize Module

Python automatically tries to import a module named usercustomize on startup from the site-packages folder.

You can create this module to execute custom init code for every Python process:

# usercustomize.py

def setup():
   print("Setting up environment!")

setup()

While it runs earlier than PYTHONSTARTUP, you lose the ability to enable/disable it on a per-process basis selectively.

2. IPython Configuration

If using IPython interactive shell instead of the default Python REPL, you can use its robust config system to customize similarly to PYTHONSTARTUP.

Simply edit ipython_config.py in IPython’s profile folder.

So while PYTHONSTARTUP is the most straightforward approach, the other options also have pros and cons to evaluate.

Best Practices

Here are some tips to use PYTHONSTARTUP effectively:

  • Import guards to prevent errors if code is imported elsewhere:if __name__ == "__main__": #Startup code
  • Version checks before using Python 3+ specific featuresimport sys if sys.version_info >= (3, 0): # Python 3 code else: # Python 2 code
  • Test interactively after making changes to catch issues early
  • Document code so future you understands it!

By following these best practices, you can avoid common pitfalls and create an awesome customized environment using PYTHONSTARTUP!

Frequently Asked Questions

Here are some common questions about customizing Python startup:

Why are my PYTHONSTARTUP functions not available when I import modules?

As mentioned earlier, only the interactive interpreter sources PYTHONSTARTUP but not imported modules. So define your utilities inside modules and explicitly import them wherever required.

How do I execute different startup code for Python 2 vs Python 3?

Use if/else checks on the Python major version to execute version-specific code like: selectively

import sys
if sys.version_info[0] == 3:
# Python 3.x code
else:
# Python 2.x code

What if I want version-specific startup files?

Unfortunately there is no direct way to achieve this in Python currently. Some workarounds are:
Write a simple script wrapper that sets PYTHONSTARTUP to different files based on version before launching python
Include version checks within one PYTHONSTARTUP file itself
So while not straightforward, it is still possible to realize version-specific customization

I hope this guide gave you a good overview of how to customize Python startup using PYTHONSTARTUP and various alternatives. The possibilities are immense – go ahead, unleash your creativity, and tune your Python environment to perfection!