Car*_*l G 14 python interpreter
我希望能够"向上箭头"到我在之前的Python解释器中输入的命令.我发现readline它提供了类似的功能模块:read_history_file,write_history_file,和set_startup_hook.虽然我还不够精明,但有人可以帮忙吗?我对解决方案的看法是:
(1)修改.login PYTHONSTARTUP以运行python脚本.(2)在那个python脚本文件中执行以下操作:
def command_history_hook():
import readline
readline.read_history_file('.python_history')
command_history_hook()
Run Code Online (Sandbox Code Playgroud)
(3)每当解释器退出时,将历史记录写入文件.我想最好的方法是在你的启动脚本中定义一个函数并使用该函数退出:
def ex():
import readline
readline.write_history_file('.python_history')
exit()
Run Code Online (Sandbox Code Playgroud)
不过要用括号退出是非常烦人的:ex().是否有一些python糖允许ex(没有parens)运行该ex功能?
是否有更好的方法可以使历史文件每次都写入?提前感谢所有解决方案/建议.
此外,我可以看到有两种架构选择.一种选择是拥有统一的命令历史记录.好处是简单(后面窝你的home目录有很多文件的替代品.)的缺点是,你在不同的终端上运行口译将与对方的命令历史记录进行填充,它们将覆盖彼此的历史.(因为我通常是在关闭一个解释,并立即重新打开一个重新加载模块感兴趣,在这种情况下,这个解释器中的命令将被写入文件,这是没有问题啊.)一个可能的解决方案,以保持每个终端独立的历史文件是为您创建的每个新终端编写环境变量:
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()
Run Code Online (Sandbox Code Playgroud)
通过将随机密钥长度从16减少到1,您可以将丢失目录的文件数减少到36,但代价是可能的重叠(2.8%).
ars*_*ars 13
我认为Python文档中的建议几乎涵盖了你想要的东西.查看第13.3节末尾的示例pystartup文件:
或看到这个页面:
但是,对于提供所有这些以及更多内容的开箱即用的交互式shell,请看一下使用IPython:
| 归档时间: |
|
| 查看次数: |
12602 次 |
| 最近记录: |