我发现自己经常使用Python的解释器来处理数据库、文件等--基本上是大量手动格式化半结构化数据。我没有像我希望的那样经常正确地保存和清理有用的部分。有没有办法将我的输入保存到shell中(db连接、变量赋值、较少的for循环和少量逻辑) --一些交互会话的历史记录?如果我使用像script
这样的东西,我会得到太多的stdout噪音。我真的不需要对所有对象都进行筛选--尽管如果有一个解决方案可以做到这一点,那就没问题了。理想情况下,我会留下一个像我交互创建的脚本一样运行的脚本,我可以只删除我不需要的部分。有没有能做到这一点的软件包,或者DIY方法?
发布于 2012-03-15 21:06:36
http://www.andrewhjon.es/save-interactive-python-session-history
import readline
readline.write_history_file('/home/ahj/history')
发布于 2009-06-03 23:23:21
有一个way可以做到这一点。将文件存储在~/.pystartup
中...
# Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
# bound to the Esc key by default (you can change it - see readline docs).
#
# Store the file in ~/.pystartup, and set an environment variable to point
# to it: "export PYTHONSTARTUP=/home/user/.pystartup" in bash.
#
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the
# full path to your home directory.
import atexit
import os
import readline
import rlcompleter
historyPath = os.path.expanduser("~/.pyhistory")
def save_history(historyPath=historyPath):
import readline
readline.write_history_file(historyPath)
if os.path.exists(historyPath):
readline.read_history_file(historyPath)
atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath
然后在shell中设置环境变量PYTHONSTARTUP
(例如在~/.bashrc
中):
export PYTHONSTARTUP=$HOME/.pystartup
您还可以添加以下内容以免费获得自动补全功能:
readline.parse_and_bind('tab: complete')
请注意,这只适用于*nix系统。As readline仅在Unix平台上可用。
发布于 2014-10-31 05:12:48
在安装Ipython并通过运行以下命令打开Ipython会话之后:
ipython
在命令行中,只需运行以下Ipython 'magic‘命令即可自动记录整个Ipython会话:
%logstart
这将创建一个唯一命名的.py文件,并存储您的会话,以便稍后用作交互式Ipython会话或在您选择的脚本中使用。
https://stackoverflow.com/questions/947810
复制相似问题