gpt4 book ai didi

python - 如何避免在 ipython 历史记录中存储命令?

转载 作者:太空狗 更新时间:2023-10-29 17:47:40 24 4
gpt4 key购买 nike

在 bash 中,我可以通过在命令前面放置一个空格来防止将命令保存到 bash 历史记录中。我不能在 ipython 中使用这个方法。我将如何在 ipython 中执行等效操作?

最佳答案

我想我终于弄明白了。这种方法并没有真正“阻止”ipython 记录历史记录,而是实际上删除 历史记录。但我认为这仍然是实现这一目标的好方法。

ipython 历史存储在 $(ipython locate)/profile_default/history.sqlite 中的 sqlite 数据库 文件中。

数据库表History有四列:sessionlinesourcesource_raw session列为当前 session 的session_id,可以通过ipython中的方法获取:get_ipython().history_manager.hisdb.get_last_session_id()ipython 中。 line 列只是行号。

所以我要做的是在 ipython 环境中删除数据库中的这条记录:

1) 在ipython中使用get_ipython().history_manager.db可以获取历史数据库对象

hismgr = get_ipython().history_manager   

2) 获取 session id:

session_id = hismgr.get_last_session_id()

3) 删除带有line_id(此处假设为111)和session_id

的历史行
hismgr.db.execute('DELETE FROM history WHERE line={0} and session={1}'.format(111, session_id))

4) InOut Array List 也有点像历史,但它存储在内存中,所以它可以像变量一样被清除或重写。

In[111]=Out[111]=''

'防止命令被保存到ipython历史',意味着删除该行在数据库中的历史记录,并重写InOut ipython 环境中的数组。我们可以将这四行合并为一条,一次性完成所有工作。 这是一个示例,如果我们要删除第 128 行:

In [127]: history -l 3 -n
124: history -l 3 -n
125: hismgr = get_ipython().history_manager; session_id = hismgr.get_last_session_id();hismgr.db.execute('DELETE FROM history WHERE line={0} and session={1}'.format(123, session_id))
126: history -l 3 -n

In [128]: passwd='123456'

In [129]: hismgr = get_ipython().history_manager; session_id = hismgr.get_last_session_id();hismgr.db.execute('DELETE FROM history WHERE line={0} and session={1}'.format(128, session_id));In[128]=Out[128]='';
Out[129]: <sqlite3.Cursor at 0x7f8dce3dae30>

In [130]: history -l 3 -n
126: history -l 3 -n
127: history -l 3 -n
129: hismgr = get_ipython().history_manager; session_id = hismgr.get_last_session_id();hismgr.db.execute('DELETE FROM history WHERE line={0} and session={1}'.format(128, session_id));In[128]=Out[128]='';

历史第 128 行没有了。

这是我浏览过的一些文档

IPython.core.history.HistoryManager

python-sqlite3

关于python - 如何避免在 ipython 历史记录中存储命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35093576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com