I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like script I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach?


当前回答

我再提一个建议: 世爵

它有历史日志和变量资源管理器。如果你用过MatLab,你就会发现其中的相似之处。

其他回答

如果使用bpython,所有的命令历史都会默认保存到~/.pythonhist。

要保存命令以供以后重用,您可以将它们复制到python脚本文件中:

$ cp ~/.pythonhist mycommands.py

然后编辑该文件以清理它并将其放在Python路径下(全局或虚拟环境的site-packages,当前目录,在*.pth中提到,或其他方式)。

要将命令包含到你的shell中,只需从保存的文件中导入它们:

>>> from mycommands import *

此外,reinteraction为Python会话提供了一个类似笔记本的界面。

来自安德鲁·琼斯的网站(存档):

import readline
readline.write_history_file('/home/ahj/history')

你可以用内置函数打开:我用它在我的所有 我需要存储一些历史的程序(包括计算器等) 例如:

#gk-test.py or anything else would do
try: # use the try loop only if you haven't created the history file outside program
    username = open("history.txt").readline().strip("\n")
    user_age = open("history.txt").readlines()[1].strip("\n")
except FileNotFoundError:
    username = input("Enter Username: ")
    user_age = input("Enter User's Age: ")
    open("history.txt", "w").write(f"{username}\n{user_age}")
#Rest of the code is secret! try it your own!

我要感谢所有喜欢我评论的人!感谢您的阅读!

%history命令非常棒,但不幸的是,它不能让您将%paste 'd保存到sesh中。要做到这一点,我认为你必须在开头执行%logstart(尽管我还没有确认这是有效的)。

我喜欢做的是

%history -o -n -p -f filename.txt

它将在每个输入(o, n和p选项)之前保存输出,行号和'>>>'。请在这里查看文档中的%history。