且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-09-21 20:25:03

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

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

  • 在用户目录下新建".pythonstartup"文件,写入以下内容:
给python交互式命令行增加自动补全和命令历史
# 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
给python交互式命令行增加自动补全和命令历史

 

  • 增加环境变量,编辑.bashrc或.zshrc文件(根据你的shell确定),加入以下内容:
export PYTHONSTARTUP="/home/ma6174/.pythonstartup"

 

  • 从新打开终端,进入python交互式命令行界面试一下。下面是我的运行效果截图:

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


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

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


本文转自ma6174博客园博客,原文链接:http://www.cnblogs.com/ma6174/archive/2013/01/05/2845776.html,如需转载请自行联系原作者