python实现定制交互式命令行的方法

yipeiwu_com5年前Python基础

Python的交互式命令行可通过启动文件来配置。

当Python启动时,会查找环境变量PYTHONSTARTUP,并且执行该变量中所指定文件里的程序代码。该指定文件名称以及地址可以是随意的。按Tab键时会自动补全内容和命令历史。这对命令行的有效增强,而这些工具则是基于readline模块实现的(这需要readline程序库辅助实现)。

此处为大家举一个简单的启动脚本文件例子,它为python命令行添加了按键自动补全内容和历史命令功能。

[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

设置环境变量

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

验证Tab键补全和历史命令查看。

[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

注意:如果在make的时候出现:

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

如果对此忽略了的话,import readline会报错。表示没有指定模块!

这里是缺少指定包:

redhat:   readline-devel.xxx.rpm

安装上重新编译执行,问题即可得到解决。

相关文章

python ftplib模块使用代码实例

这篇文章主要介绍了python ftplib模块使用代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Python中默认安装的f...

python使用opencv对图像mask处理的方法

python使用opencv对图像mask处理的方法

MASK图像掩膜处理 在图像操作中有时候会用到掩膜处理,如果使用遍历法掩膜图像ROI区域对于python来讲是很慢的,所以我们要找到一种比较好的算法来实现掩膜处理。 假设我们有一副图...

pyqt5 禁止窗口最大化和禁止窗口拉伸的方法

如下所示: 在def __init__(self):函数里添加 self.setFixedSize(self.width(), self.height()) 以上这篇pyqt5 禁止窗口...

给你选择Python语言实现机器学习算法的三大理由

给你选择Python语言实现机器学习算法的三大理由

基于以下三个原因,我们选择Python作为实现机器学习算法的编程语言:(1) Python的语法清晰;(2) 易于操作纯文本文件;(3) 使用广泛,存在大量的开发文档。 可执行伪代码 P...

python得到一个excel的全部sheet标签值方法

这里需要用到python处理excel很经典的库openpyxl,安装也特别简单。window直接pip install就好了 代码在这里~ wb = openpyxl.load_w...