unm*_*ted 404 python shell read-eval-print-loop interactive-session
我发现自己经常使用Python的解释器来处理数据库,文件等 - 基本上是大量的半结构化数据的手动格式化.我没有像我希望的那样经常保存和清理有用的位.有没有办法将我的输入保存到shell中(数据库连接,变量赋值,少量循环和逻辑位) - 交互式会话的一些历史记录?如果我使用像script我得到太多stdout噪音的东西.我真的不需要腌制所有对象 - 但如果有一个解决方案可以做到这一点,那就没关系.理想情况下,我只剩下一个脚本,它以我交互式创建的脚本运行,我可以删除我不需要的位.有没有这样做的包,或DIY方法?
更新:我对这些包的质量和实用性感到非常惊讶.对于那些有类似痒的人:
我被转换了,这些真正填补了翻译和编辑之间的需要.
Ant*_*sma 396
如果您喜欢使用交互式会话,IPython非常有用.例如,对于您的用例,有一个%save魔术命令,您只需输入%save my_useful_session 10-20 23以保存输入行10到20和23 my_useful_session.py(为了帮助它,每行都以其编号为前缀).
此外,文件说明:
此函数使用与输入范围的%history相同的语法,然后将行保存到您指定的文件名.
这允许例如引用较旧的会话,例如
%save current_session ~0/
%save previous_session ~1/
Run Code Online (Sandbox Code Playgroud)
小智 152
http://www.andrewhjon.es/save-interactive-python-session-history
import readline
readline.write_history_file('/home/ahj/history')
Run Code Online (Sandbox Code Playgroud)
Nad*_*mli 91
有办法做到这一点.将文件存储在~/.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
Run Code Online (Sandbox Code Playgroud)
然后PYTHONSTARTUP在shell中设置环境变量(例如~/.bashrc):
export PYTHONSTARTUP=$HOME/.pystartup
Run Code Online (Sandbox Code Playgroud)
您还可以添加此项以免费获得自动填充功能:
readline.parse_and_bind('tab: complete')
Run Code Online (Sandbox Code Playgroud)
请注意,这仅适用于*nix系统.由于readline仅适用于Unix平台.
nac*_*uve 72
如果您正在使用IPython,您可以使用带有-f参数pe 的魔术函数%history将所有以前的命令保存到文件中:
%history -f /tmp/history.py
Run Code Online (Sandbox Code Playgroud)
小智 18
安装Ipython之后,通过运行命令打开Ipython会话:
ipython
Run Code Online (Sandbox Code Playgroud)
从命令行,只需运行以下Ipython'magic'命令即可自动记录整个Ipython会话:
%logstart
Run Code Online (Sandbox Code Playgroud)
这将创建一个唯一命名的.py文件并存储您的会话,以便以后用作交互式Ipython会话或用于您选择的脚本.
Ned*_*der 14
此外,reinteract为您提供了一个类似于笔记本的Python会话界面.
我不得不努力寻找答案,我对iPython环境很新.
这会奏效
如果您的iPython会话看起来像这样
In [1] : import numpy as np
....
In [135]: counter=collections.Counter(mapusercluster[3])
In [136]: counter
Out[136]: Counter({2: 700, 0: 351, 1: 233})
Run Code Online (Sandbox Code Playgroud)
您希望保存从1到135的行,然后在同一个ipython会话中使用此命令
In [137]: %save test.py 1-135
Run Code Online (Sandbox Code Playgroud)
这将保存当前目录(启动ipython的地方)中test.py文件中的所有python语句.
| 归档时间: |
|
| 查看次数: |
174890 次 |
| 最近记录: |