Expert Python Programming(Third Edition)
上QQ阅读APP看书,第一时间看更新

Custom Python shells – ipython, bpython, ptpython, and so on

Python programmers spend a lot of time in interactive interpreter sessions. It is very good for testing small code snippets, accessing documentation, or even debugging code at runtime. The default interactive Python session is very simple, and does not provide many features, such as tab completion or code introspection helpers. Fortunately, the default Python shell can be easily extended and customized.

If you use an interactive shell very often, you can easily modify the behavior of it prompt. Python at startup reads the PYTHONSTARTUP environment variable, looking for the path of the custom initializations script. Some operating system distributions where Python is a common system component (for example, Linux, macOS) may be already preconfigured to provide a default startup script. It is commonly found in the users, home directory under the .pythonstartup name. These scripts often use the readline module (based on the GNU readline library) together with rlcompleter in order to provide interactive tab completion and command history.

If you don't have a default python startup script, you can easily build your own. A basic script for command history and tab completion can be as simple as the following:

# python startup file 

import atexit 
import os 
 
try:
import readline
except ImportError:
print("Completion unavailable: readline module not available")
else:
import rlcompleter
# tab completion readline.parse_and_bind('tab: complete') # Path to history file in user's home directory.
# Can use your own path. history_file = os.path.join(os.environ['HOME'], '.python_shell_history') try: readline.read_history_file(history_file) except IOError: pass atexit.register(readline.write_history_file, history_file) del os, history_file, readline, rlcompleter

Create this file in your home directory and call it .pythonstartup. Then, add a PYTHONSTARTUP variable in your environment using the path of your file.