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,你就会发现其中的相似之处。

其他回答

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

我喜欢做的是

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

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

如果您喜欢使用交互式会话,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/

查看演示页面上的视频以快速了解功能。

有一种方法可以做到。将文件存储在~/.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系统。因为readline只在Unix平台上可用。

如果你正在使用IPython,你可以使用神奇的%history函数和-f参数p.e将你之前的所有命令保存到一个文件中:

%history -f /tmp/history.py

除了IPython之外,类似的实用程序bpython还有一个“将您输入的代码保存到文件中”的特性