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?
当前回答
在IPython中,我首先使用
In [2]: %hist
查看我过去的代码。我选择我想要保存的块,然后使用%%文件魔法(%%writefile的缩写)将其粘贴到文件my_file.py中。
In [3]: %%file my_file.py
...: # paste code here
...:
...:
最后按了两次回车键。
使用选项-a: %%file -a my_file.py追加文件。
如果需要,我可以在底层命令行中使用感叹号列出、编辑文件等
In [5]: !ls -l my_file.py
In [6]: !vi my_file.py
其他回答
来自安德鲁·琼斯的网站(存档):
import readline
readline.write_history_file('/home/ahj/history')
除了IPython之外,类似的实用程序bpython还有一个“将您输入的代码保存到文件中”的特性
如果你正在使用IPython,你可以使用神奇的%history函数和-f参数p.e将你之前的所有命令保存到一个文件中:
%history -f /tmp/history.py
一些评论询问如何一次保存所有的IPython输入。对于IPython中的%save魔术,您可以以编程方式保存所有命令,如下所示,以避免提示消息,也避免指定输入数字。 currentLine = len(In)-1 %save -f my_session 1-$currentLine
f选项用于强制替换文件,len(IN)-1显示IPython中的当前输入提示符,允许您以编程方式保存整个会话。
我再提一个建议: 世爵
它有历史日志和变量资源管理器。如果你用过MatLab,你就会发现其中的相似之处。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 查看PS命令的全部输出
- 使用try和。Python中的if