For those unfamiliar with ~/.bashrc, it is a customizable script that exists for the Unix shell Bash
. When a new terminal session begins, this user-specific file is run. Users can script common variables, functions, and environment settings in this file and thus have them automatically loaded whenever they open a terminal window.
Does something analogous exist for Python? Essentially I would like to define a handful of global Python functions in a script and ensure that they are loaded whenever I run a Python script on my machine, or whenever I start a Python terminal. I am wondering if this behavior already exists, or if there is a straight-forward way to implement it.
The . bashrc file is a script file that's executed when a user logs in. The file itself contains a series of configurations for the terminal session. This includes setting up or enabling: coloring, completion, shell history, command aliases, and more. It is a hidden file and simple ls command won't show the file.
In most cases, the bashrc is a hidden file that lives in your home directory, its path is ~/. bashrc or {USER}/. bashrc with {USER} being the login currently in use.
The quickest way to access it is nano ~/. bashrc from a terminal (replace nano with whatever you like to use). If this is not present in a user's home folder the system-wide . bashrc is used as a fallback as it is loaded before the user's file.
bashrc file is a script, and by sourcing it, you execute the commands placed in that file. The commands define aliases in your case, but there can be virtually any commands placed in that file. you could also use exec bash to replace the current bash process with a new.
Running for every Python script isn't a good idea since it breaks namespacing; per Zen of Python:
Namespaces are one honking great idea -- let's do more of those!
That said, __init__.py
can be used to ensure certain code is run if a package or its children are imported, and for customizing the interactive interpreter, set the PYTHONSTARTUP
environment variable to point to a file with Python commands to run before handing off to the interactive interpreter, e.g. export PYTHONSTARTUP=$HOME/.pythonrc
.
Just make sure the PYTHONSTARTUP
file contains legal syntax for both Py2 and Py3 because there is no PYTHON3STARTUP
, it'll be run for both versions of Python.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With