cmh*_*cmh 16 python macros ipython
使用ipython时,我经常想保存我在会话期间定义的特定功能,例如:
In [1]: def func1():
...: pass
...:
In [2]: %save func1.py func1
func1 is neither a string nor a macro.
Run Code Online (Sandbox Code Playgroud)
相反,我必须从中选择函数定义行号enumerate(_ih),或者如果我有%edit函数则从vim手动复制和粘贴.
有办法实现%save func1.py func1吗?我觉得应该可以,因为ipython在使用%edit时可以访问该定义.
编辑
如果我在某些时候编辑了函数,基于行的保存不起作用%ed.我正在寻找一种在这种情况下保存新函数定义的方法.
cfe*_*ann 19
您可以保存行的内容1与%save使用:
In [2]: %save func1.py 1
The following commands were written to file `func1.py`:
def func1():
pass
Run Code Online (Sandbox Code Playgroud)
帮助%save可用于:
In [2]: %save?
Type: Magic function
...
Docstring:
Save a set of lines or a macro to a given filename.
Usage:
%save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
Run Code Online (Sandbox Code Playgroud)
你可以用%edit一个函数体:
In [3] %edit func1
done. Executing edited code...
Run Code Online (Sandbox Code Playgroud)
在完成%edit您的功能之后func1,您可以使用以下命令从IPython获取以下输出_:
In [4]: _
Out[4]: 'def func1():\n print "Hello World"\n\n'
Run Code Online (Sandbox Code Playgroud)
然后,您可以%macro使用以下更新func1内容定义或重新定义a :
In [5]: %macro new_func1_macro _
Macro `new_func1_macro` created. To execute, type its name (without quotes).
=== Macro contents: ===
def func1():
print "Hello World"
Run Code Online (Sandbox Code Playgroud)
最后,您可以像这样保存新版本的func1with %save和new %macro:
In [6]: %save func1.py new_func1_macro
The following commands were written to file `func1.py`:
def func1():
print "Hello World"
Run Code Online (Sandbox Code Playgroud)
希望澄清一下.
In [1]: def a():
...: print('hello')
...: return
In [2]: from inspect import getsource
In [3]: %save a.py getsource(a)
The following commands were written to file `a.py`:
def a():
print('hello')
return
Run Code Online (Sandbox Code Playgroud)