如果您喜欢使用交互式会话, IPython非常有用。 例如你的用例有%save magic命令 ,你只需input%save my_useful_session 10-20 23将input行10到20和23保存到my_useful_session.py (为了解决这个问题,每一行都以其前缀数)。
此外,该文件指出:
此函数使用与%history相同的语法input范围,然后将行保存为您指定的文件名。
这允许例如引用较旧的会话,例如
%save current_session ~0/ %save previous_session ~1/
查看演示页面上的video以快速浏览function。
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