首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何保存Python交互会话?

如何保存Python交互会话?
EN

Stack Overflow用户
提问于 2009-06-04 07:21:03
回答 13查看 208.7K关注 0票数 441

我发现自己经常使用Python的解释器来处理数据库、文件等--基本上是大量手动格式化半结构化数据。我没有像我希望的那样经常正确地保存和清理有用的部分。有没有办法将我的输入保存到shell中(db连接、变量赋值、较少的for循环和少量逻辑) --一些交互会话的历史记录?如果我使用像script这样的东西,我会得到太多的stdout噪音。我真的不需要对所有对象都进行筛选--尽管如果有一个解决方案可以做到这一点,那就没问题了。理想情况下,我会留下一个像我交互创建的脚本一样运行的脚本,我可以只删除我不需要的部分。有没有能做到这一点的软件包,或者DIY方法?

EN

回答 13

Stack Overflow用户

发布于 2012-03-15 21:06:36

http://www.andrewhjon.es/save-interactive-python-session-history

代码语言:javascript
复制
import readline
readline.write_history_file('/home/ahj/history')
票数 188
EN

Stack Overflow用户

发布于 2009-06-03 23:23:21

有一个way可以做到这一点。将文件存储在~/.pystartup中...

代码语言:javascript
复制
# 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中):

代码语言:javascript
复制
export PYTHONSTARTUP=$HOME/.pystartup

您还可以添加以下内容以免费获得自动补全功能:

代码语言:javascript
复制
readline.parse_and_bind('tab: complete')

请注意,这只适用于*nix系统。As readline仅在Unix平台上可用。

票数 98
EN

Stack Overflow用户

发布于 2014-10-31 05:12:48

在安装Ipython并通过运行以下命令打开Ipython会话之后:

代码语言:javascript
复制
ipython

在命令行中,只需运行以下Ipython 'magic‘命令即可自动记录整个Ipython会话:

代码语言:javascript
复制
%logstart

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

票数 21
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/947810

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档