目录

给python交互式命令行增加自动补全和命令历史

目录

给python交互式命令行增加自动补全和命令历史

转载至:

考完试了,开始研究《python高级编程》

用过zsh的同学肯定对其自动补全功能印象深刻,通过简单的定制python交互式命令行也能实现类似功能,具体操作如下:

  • 在用户目录下新建".pythonstartup"文件,写入以下内容:
# python startup file
import readline
import rlcompleter
import atexit
import os
#tab completion
readline.parse_and_bind('tab: complete')
#history file
historyfile = os.path.join(os.environ['HOME'],'.pythonstartup')
try:
    readline.read_history_file(historyfile)
except:
    pass
atexit.register(readline.write_history_file,historyfile)
del os,historyfile,readline,rlcompleter
  • 增加环境变量,编辑.bashrc或.zshrc文件(根据你的shell确定),加入以下内容:
export PYTHONSTARTUP="/home/ma6174/.pythonstartup"
  • 从新打开终端,进入python交互式命令行界面试一下。下面是我的运行效果截图:

http://images.cnitblog.com/blog/353475/201301/05143359-544ae8fe97844d2ca048e4523d779f46.png


博主ma6174对本博客文章(除转载的)享有版权,未经许可不得用于商业用途。转载请注明出处

对文章有啥看法或建议,可以评论或发电子邮件到ma6174@163.com