python - 将 Python 解释器历史导出到文件?

标签 python

在我实际写入文件之前,我会使用 Python 解释器检查变量并逐步执行命令。但是到最后,我在解释器中有大约 30 个命令,并且必须将它们复制/粘贴到文件中才能运行。有没有办法可以将 Python 解释器历史导出/写入文件?

例如

>>> a = 5
>>> b = a + 6
>>> import sys
>>> export('history', 'interactions.py') 

然后我可以打开 interactions.py 文件并阅读:

a = 5
b = a + 6
import sys

最佳答案

IPython如果您喜欢使用交互式 session ,则非常有用。例如,对于您的用例,有 save 命令,您只需输入 save my_useful_session 10-20 23 即可将输入行 10 到 20 和 23 保存到 my_useful_session.py。 (为了帮助解决这个问题,每一行都以它的编号为前缀)

查看文档页面上的视频以快速了解这些功能。

::OR::

有一个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

您还可以添加它以免费获得自动完成功能:

readline.parse_and_bind('tab: complete')

请注意,这只适用于 *nix 系统。由于 readline 仅适用于 Unix 平台。

关于python - 将 Python 解释器历史导出到文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8421097/

相关文章:

python - 正则表达式在多种条件下匹配版权声明中的公司名称

python - 数据框中行和列之间的交互

python - "has:()"和 "not:()"伪类在 BeautifulSoup 中使用时表现不同

python - virtualenv 和 CLI 工具

python - 错误 : nothing to repeat at position 0 using regex in python

python - 我可以从 SQLAlchemy 中获取纯数组而不是字典的行吗?

Python正则表达式如何在字母和数字之间插入连字符;并删除两个字母之间的连字符

python - 将python中的数组列表转换为grasshopper中的树

python - MLP 中的 Theano 批量学习,偏差形状

python - ResourceWarning : python-memcached not closing socket?