Python implements methods for customizing interactive command lines

  • 2020-04-02 13:48:57
  • OfStack

Python's interactive command line can be configured by launching a file.

When Python starts, it looks for the environment variable Python startup and executes the program code in the file specified in that variable. The specified file name and address can be arbitrary. Press the Tab key to complete the content and command history automatically. This effectively enhances the command line, and these tools are implemented based on the readline module (which requires a readline library helper implementation).

Here's a simple example of a startup script file that adds auto-completion and historical commands to the python command line.


[python@python ~]$ cat .pythonstartup
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

Setting environment variables


[python@python ~]$ cat .bash_profile|grep PYTHON
export PYTHONSTARTUP=/home/python/.pythonstartup

Verify Tab key completion and history command view.


[python@python ~]$ python
Python 2.7.5 (default, Oct 6 2013, 10:45:13)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import md5
>>> md5.
md5.__class__(     md5.__getattribute__( md5.__reduce__(    md5.__subclasshook__(
md5.__delattr__(    md5.__hash__(     md5.__reduce_ex__(   md5.blocksize
md5.__dict__      md5.__init__(     md5.__repr__(     md5.digest_size
md5.__doc__      md5.__name__      md5.__setattr__(    md5.md5(
md5.__file__      md5.__new__(      md5.__sizeof__(    md5.new(
md5.__format__(    md5.__package__    md5.__str__(      md5.warnings
>>> import os
>>> import md5

Note: if it appears in make:


Python build finished, but the necessary bits to build these modules were not found:
_tkinter            gdbm      readline      sunaudiodev

If this is ignored, import readline reports an error. No module specified!

Here is the missing specified package:


redhat:   readline-devel.xxx.rpm

Recompile the execution on the installation and the problem will be resolved.


Related articles: