Let's find out what PYTHONSTARTUP is and how can we use it.

To The Point

According to documentation:


If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode. The file is executed in the same namespace where interactive commands are executed so that objects defined or imported in it can be used without qualification in the interactive session. You can also change the prompts sys.ps1 and sys.ps2 and the hook sys.interactivehook in this file.

To put it into perspective, let's check how to use it.

Let's create a .pythonrc file with this:


Then lets setup PYTHONSTARTUP with this bash command:

export PYTHONSTARTUP=~/.pythonrc

Now let's call python interactive mode with python, and you will find something similar to this:

Python 2.7.6 (default, Nov 23 2017, 15:49:48)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.

It means that we basically were able to hack into interactive mode before starting of it.

This works only on an interactive mode.

Examples of pythonrc

Rasadacrea example of pythonrc gives us possibility to use tab completion :

import readline
import rlcompleter
import atexit
import os
# tab completion
readline.parse_and_bind('tab: complete')
# history file
histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
except IOError:
atexit.register(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter



Related links


That's it :) Comment, share or don't - up to you.

Any suggestions what I should blog about? Post me a comment in the box below or poke me at Twitter: @anselmos88.

See you in the next episode! Cheers!


comments powered by Disqus