Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of ~/.bashrc

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.

like image 891
Jake Avatar asked Jan 30 '16 05:01

Jake


People also ask

What is the ~/ bashrc file?

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.

Where can I find ~/ bashrc?

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.

How do I open ~/ bashrc?

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.

What is the use of source ~/ bashrc?

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.


1 Answers

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.

like image 56
ShadowRanger Avatar answered Oct 03 '22 22:10

ShadowRanger