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

其他回答

你可以用内置函数打开:我用它在我的所有 我需要存储一些历史的程序(包括计算器等) 例如:

#gk-test.py or anything else would do
try: # use the try loop only if you haven't created the history file outside program
    username = open("history.txt").readline().strip("\n")
    user_age = open("history.txt").readlines()[1].strip("\n")
except FileNotFoundError:
    username = input("Enter Username: ")
    user_age = input("Enter User's Age: ")
    open("history.txt", "w").write(f"{username}\n{user_age}")
#Rest of the code is secret! try it your own!

我要感谢所有喜欢我评论的人!感谢您的阅读!

有一种方法可以做到。将文件存储在~/.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中设置环境变量PYTHONSTARTUP(例如在~/.bashrc中):

export PYTHONSTARTUP=$HOME/.pystartup

你也可以添加这个来获得免费的自动补全:

readline.parse_and_bind('tab: complete')

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

来自安德鲁·琼斯的网站(存档):

import readline
readline.write_history_file('/home/ahj/history')

有%history魔法用于打印和保存输入历史记录(可选的还有输出)。

将当前会话存储到my_history.py文件中:

>>> %hist -f my_history.py

History IPython存储您输入的命令和它产生的结果。您可以使用上下方向键轻松地浏览以前的命令,或者以更复杂的方式访问历史记录。

您可以使用%history神奇函数来检查过去的输入和输出。以前会话的输入历史保存在数据库中,可以配置IPython以保存输出历史。

其他几个神奇的功能可以使用您的输入历史,包括%编辑,%重新运行,%召回,%宏,%保存和%pastebin。你可以使用标准格式来引用行:

%pastebin 3 18-20 ~1/1-5

这将占用当前会话中的第3行和第18 - 20行,以及前一会话中的第1-5行。

看到%历史吗?查看Docstring和更多示例。

另外,一定要探索%store magic在IPython中实现变量轻量级持久性的功能。

在IPython的数据库中存储变量、别名和宏。

d = {'a': 1, 'b': 2}
%store d  # stores the variable
del d

%store -r d  # Refresh the variable from IPython's database.
>>> d
{'a': 1, 'b': 2}

要在启动时自动恢复存储的变量,ipython_config.py中的specificc . storemagic .autorestore = True。

还有另一种选择——耻骨瓣切除术。 在“wxpython 2.8文档演示和工具”中,有一个名为“pyslices”的开源程序。

你可以像编辑器一样使用它,它也支持像控制台一样使用----,像交互式解释器一样执行每一行,具有即时回显。

当然,所有的代码块和每个块的结果都会自动记录到一个TXT文件中。

结果被记录在相应代码块的后面。非常方便。