Python Startup 脚本

这段是在《Python高级编程》看到的,觉得很有用,PO上来。

python命令行程序启动时会查找环境变量PYTHONSTARTUP,并且执行该变量中所指定文件里的程序代码。有些linux发行版本提供了一个默认的启动脚本,它通常放在用户的主目录下,文件名是.pythonstartup。按Tab键时自动补全内容和命令历史。


Python

# python startup file
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

在用户主目录下创建该文件,命名为.pythonstartup,添加环境变量PYTHONSTARTUP。(可以在.profile中写export PYTHONSTARTUP=~/.pythonstartup)

当启动交互式命令行时,将会执行.pythonstartup脚本,这些功能将被启用。例如按Tab键会自动补全内容。

>>> import md5

>>> md5.<tab>

md5.__class__  md5.md5 ...

关于python的readline module:

The readline module defines a number of functions to facilitate completion and reading/writing of history files from the Python interpreter. This module can be used directly or via the rlcompleter module.

– EOF –

5 comments:

  1. Donly

    请问在Mac OS上如何添加呢,貌似没有.profile,在~/下新建一个也不行呢

  2. https://idohomework.net/

    Article Source: Szasz is an expert when it comes to Top
    Exercise Equipment,Treadmills,Exercise Equipment.
    What can we do together creatively to get that rate
    down. Many people mistake the symptoms of a panic attack for a heart attack.

  3. Bettye

    Good post. I learn something new and challenging on blogs I stumbleupon everyday.

    It’s always helpful to read through articles
    from other writers and use a little something from their
    websites.

Leave a Reply

Your email address will not be published. Required fields are marked *