Let's find out what PYTHONSTARTUP is and how can we use it.
To The Point
According to documentation:
PYTHONSTARTUP
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:
print("how_use_pythonstartup")
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.
how_use_pythonstartup
>>>
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')
try:
readline.read_history_file(histfile)
except IOError:
pass
atexit.register(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter
Acknowledgements
Auto-promotion
Related links
- 1. Command line and environment — Python 3.6.5 documentation
- python courses : how to use the python interpreter on ubuntu, RasadaCrea Grenoble - Lyon
- python-startup/startup.py at master · jezdez-archive/python-startup · GitHub
- No history in python3 inside the virtualenv · Issue #90 · berdario/pew · GitHub
- python - Can someone tell me the purpose of PYTHONSTARTUP? - Stack Overflow
- Use PYTHONSTARTUP to interactively test a python file in the interpreter - Stack Overflow
- Brandon Invergo - Enhancing the Python interpreter with a start-up script
Thanks!
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
comments powered by Disqus