Python的交互式命令行可通過啟動文件來配置。
當Python啟動時,會查找環境變量PYTHONSTARTUP,并且執行該變量中所指定文件里的程序代碼。該指定文件名稱以及地址可以是隨意的。按Tab鍵時會自動補全內容和命令歷史。這對命令行的有效增強,而這些工具則是基于readline模塊實現的(這需要readline程序庫輔助實現)。
此處為大家舉一個簡單的啟動腳本文件例子,它為python命令行添加了按鍵自動補全內容和歷史命令功能。
[python@python ~]$ cat .pythonstartupimport readlineimport rlcompleterimport atexitimport os#tab completionreadline.parse_and_bind('tab: complete')#history filehistfile = os.path.join(os.environ['HOME'], '.pythonhistory')try: readline.read_history_file(histfile)except IOError: passatexit.register(readline.write_history_file,histfile)del os,histfile,readline,rlcompleter
設置環境變量
[python@python ~]$ cat .bash_profile|grep PYTHONexport PYTHONSTARTUP=/home/python/.pythonstartup
驗證Tab鍵補全和歷史命令查看。
[python@python ~]$ pythonPython 2.7.5 (default, Oct 6 2013, 10:45:13)[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2Type "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.blocksizemd5.__dict__ md5.__init__( md5.__repr__( md5.digest_sizemd5.__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
安裝上重新編譯執行,問題即可得到解決。
新聞熱點
疑難解答