天天看点

为Python添加交互模式下TAB自动补全以及命令历史功能

接上篇文章

新建Python环境变量配置文件:

在宿主用户目录下

vim .pystartup

# Add auto-completion and a stored history file of commands to your Python

# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is

# bound to the Esc key by default (you can change it – see readline docs).

# Store the file in ~/.pystartup, and set an environment variable to point

# to it:  “export PYTHONSTARTUP=~/.pystartup” in bash.

import atexit

import os

import readline

import rlcompleter

readline.parse_and_bind(‘tab: complete’)

historyPath = os.path.expanduser(“~/.pyhistory”)

def save_history(historyPath=historyPath):

    import readline

    readline.write_history_file(historyPath)

if os.path.exists(historyPath):

    readline.read_history_file(historyPath)

atexit.register(save_history)

del os, atexit, readline, rlcompleter, save_history, historyPath

设置python 环境变量:

永久生效:

echo “export PYTHONSTARTUP=~/.pystartup” >> /etc/profile

source /etc/profile

验证:

[root@localhost ~]# python27

Python 2.7.9 (default, Jun 29 2016, 16:05:04) 

[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2

Type “help”, “copyright”, “credits” or “license” for more information.

>>> e

elif        else        enumerate(  eval_r(       except      exec        execfile(   exit(       

      本文转自无形于有形  51CTO博客,原文链接:http://blog.51cto.com/jinchuang/1844413,如需转载请自行联系原作者