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?
当前回答
除了IPython之外,类似的实用程序bpython还有一个“将您输入的代码保存到文件中”的特性
其他回答
有%history魔法用于打印和保存输入历史记录(可选的还有输出)。
将当前会话存储到my_history.py文件中:
>>> %hist -f my_history.py
History IPython存储您输入的命令和它产生的结果。您可以使用上下方向键轻松地浏览以前的命令,或者以更复杂的方式访问历史记录。
您可以使用%history神奇函数来检查过去的输入和输出。以前会话的输入历史保存在数据库中,可以配置IPython以保存输出历史。
其他几个神奇的功能可以使用您的输入历史,包括%编辑,%重新运行,%召回,%宏,%保存和%pastebin。你可以使用标准格式来引用行:
%pastebin 3 18-20 ~1/1-5
这将占用当前会话中的第3行和第18 - 20行,以及前一会话中的第1-5行。
看到%历史吗?查看Docstring和更多示例。
另外,一定要探索%store magic在IPython中实现变量轻量级持久性的功能。
在IPython的数据库中存储变量、别名和宏。
d = {'a': 1, 'b': 2}
%store d # stores the variable
del d
%store -r d # Refresh the variable from IPython's database.
>>> d
{'a': 1, 'b': 2}
要在启动时自动恢复存储的变量,ipython_config.py中的specificc . storemagic .autorestore = True。
我不得不努力寻找答案,我对iPython环境非常陌生。
这是可行的
如果你的iPython会话是这样的
In [1] : import numpy as np
....
In [135]: counter=collections.Counter(mapusercluster[3])
In [136]: counter
Out[136]: Counter({2: 700, 0: 351, 1: 233})
你想保存从1到135的行,然后在同一个ipython会话上使用这个命令
In [137]: %save test.py 1-135
这将把你所有的python语句保存在当前目录下的test.py文件中(你启动ipython的地方)。
如果使用bpython,所有的命令历史都会默认保存到~/.pythonhist。
要保存命令以供以后重用,您可以将它们复制到python脚本文件中:
$ cp ~/.pythonhist mycommands.py
然后编辑该文件以清理它并将其放在Python路径下(全局或虚拟环境的site-packages,当前目录,在*.pth中提到,或其他方式)。
要将命令包含到你的shell中,只需从保存的文件中导入它们:
>>> from mycommands import *
如果您喜欢使用交互式会话,IPython是非常有用的。例如,在您的用例中,有一个%save magic命令,您只需输入%save my_useful_session 10-20 23,将第10行到第20行和第23行保存到my_useful_session.py(为了帮助实现这一点,每一行都有它的数字前缀)。
此外,文件指出:
此函数对输入范围使用与%history相同的语法,然后将行保存到指定的文件名。
例如,这允许引用旧的会话,例如
%save current_session ~0/
%save previous_session ~1/
查看演示页面上的视频以快速了解功能。
你可以用内置函数打开:我用它在我的所有 我需要存储一些历史的程序(包括计算器等) 例如:
#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!
我要感谢所有喜欢我评论的人!感谢您的阅读!