熱線電話:13121318867

登錄
首頁精彩閱讀python實現定制交互式命令行的方法
python實現定制交互式命令行的方法
2018-03-08
收藏

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
安裝上重新編譯執行,問題即可得到解決。

數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢