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?


当前回答

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

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

其他回答

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

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

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

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

%history -f /tmp/history.py

在安装Ipython并打开Ipython会话后,执行以下命令:

ipython

在你的命令行中,只需运行下面的Ipython 'magic'命令来自动记录你的整个Ipython会话:

%logstart

这将创建一个唯一命名的.py文件,并存储您的会话,以供以后作为交互式Ipython会话使用或在您选择的脚本中使用。

就Linux而言,人们可以使用脚本命令来记录整个会话。它是util-linux包的一部分,所以应该在大多数Linux系统上。你可以创建一个别名或函数,调用script -c python,并保存到typescript文件中。例如,这里有一个这样的文件的再版。

$ cat typescript                                                                                                      
Script started on Sat 14 May 2016 08:30:08 AM MDT
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'Hello Pythonic World'
Hello Pythonic World
>>> 

Script done on Sat 14 May 2016 08:30:42 AM MDT

这里的一个小缺点是,脚本会记录所有内容,甚至换行,无论何时点击退格等等。所以你可能想使用col来清理输出(参见这篇关于Unix&Linux Stackexchange的文章)。