gpt4 book ai didi

python - 创建 Ipython magic 命令以将最后一个控制台输入保存到文件中

转载 作者:太空宇宙 更新时间:2023-11-03 18:38:19 24 4
gpt4 key购买 nike

备注现在我找到了解决方案。我想在 ipython 中实现我自己的神奇命令,它将最后的输入保存到 python 文件中,以便交互式地生成可执行的 python 代码:我考虑过将其保存为自己的magicfile.py在ipython启动目录中:

#Save this file in the ipython profile startup directory which can be found via:
#import IPython
#IPython.utils.path.locate_profile()
from IPython.core.magic import (Magics, magics_class, line_magic,
cell_magic, line_cell_magic)

# The class MUST call this class decorator at creation time
@magics_class
class MyMagics(Magics):

@line_magic
def s(self, line):
import os
import datetime
today = datetime.date.today()
get_ipython().magic('%history -l 1 -t -f history.txt /')
with open('history.txt', 'r') as history:
lastinput = history.readline()
with open('ilog_'+str(today)+'.py', 'a') as log:
log.write(lastinput)
os.remove('history.txt')
print 'Successfully logged to ilog_'+str(today)+'.py!'

# In order to actually use these magics, you must register them with a
# running IPython. This code must be placed in a file that is loaded once
# IPython is up and running:
ip = get_ipython()
# You can register the class itself without instantiating it. IPython will
# call the default constructor on it.
ip.register_magics(MyMagics)

所以现在我在 ipython 中输入命令,然后 s;并将其附加到今天的日志文件中。

最佳答案

使用附加参数 -a 和 %save。

如果这是您要保存的行:

In [10]: print 'airspeed velocity of an unladen swallow: '

然后像这样保存:

In [11]: %save -a IPy_session.py 10
The following commands were written to file `IPy_session.py`:
print 'airspeed velocity of an unladen swallow: '

请参阅Ipython %save documentation

关于python - 创建 Ipython magic 命令以将最后一个控制台输入保存到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21114684/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com