我希望能够“向上箭头”指向我在以前的 Python 解释器中输入的命令。我已经找到了readline
模块提供以下功能:read_history_file
, write_history_file
, and set_startup_hook
。我还不够聪明,无法将其付诸实践,所以有人可以帮忙吗?我对解决方案的想法是:
(1)修改.login PYTHONSTARTUP来运行python脚本。
(2) 在该 python 脚本文件中执行以下操作:
def command_history_hook():
import readline
readline.read_history_file('.python_history')
command_history_hook()
(3)每当解释器退出时,将历史记录写入文件。我想最好的方法是在启动脚本中定义一个函数并使用该函数退出:
def ex():
import readline
readline.write_history_file('.python_history')
exit()
不过,必须使用括号退出是非常烦人的:ex()
。有没有一些蟒蛇糖可以让ex
(不带括号)运行ex
功能?
有没有更好的方法让历史文件每次都写入?预先感谢所有解决方案/建议。
此外,据我所知,有两种架构选择。一种选择是拥有统一的命令历史记录。好处是简单(后面的替代方案会在您的主目录中散布大量文件。)缺点是您在单独终端中运行的解释器将填充彼此的命令历史记录,并且它们将覆盖彼此的历史记录。 (这对我来说没问题,因为我通常有兴趣关闭解释器并立即重新打开解释器以重新加载模块,在这种情况下,解释器的命令将被写入文件中。)一种可能的解决方案是为每个终端维护单独的历史文件是为您创建的每个新终端编写一个环境变量:
def random_key()
''.join([choice(string.uppercase + string.digits) for i in range(16)])
def command_history_hook():
import readline
key = get_env_variable('command_history_key')
if key:
readline.read_history_file('.python_history_{0}'.format(key))
else:
set_env_variable('command_history_key', random_key())
def ex():
import readline
key = get_env_variable('command_history_key')
if not key:
set_env_variable('command_history_key', random_key())
readline.write_history_file('.python_history_{0}'.format(key))
exit()
通过将随机密钥长度从 16 减少到 1,您可以将目录中散乱的文件数量减少到 36,但代价是可能存在重叠(2.8% 的机会)。