获取到目前为止在 Python 解释器会话中输入的代码
Get code entered so far in Python interpreter session
到目前为止,是否有一种快速、方便的方法将所有代码输入 python 解释器?例如,如果我在解释器中输入:
Steven$ python
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hi"
hi
>>> a = [1,2,3]
>>> for e in a:
... print e
...
1
2
3
>>> print "bye"
bye
>>>
我想得到这些行:
print "hi"
a = [1,2,3]
for e in a:
print e
print "bye"
%history 魔法函数应该为您完成。
In [1]: l = [1,2,3]
In [2]: %history
l = [1,2,3]
%history
如果您发现自己经常这样做,请考虑使用 ipython notebook.
您可以使用 readline
模块。
Python 2.7.5 (default, Nov 3 2014, 14:26:24)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hi"
hi
>>> a = [1,2,3]
>>> for e in a:
... print e
...
1
2
3
>>> print "bye"
bye
>>> import readline
>>> readline.write_history_file('history.py')
文件 history.py
将包含您的历史记录,包括最后两行:
$ cat history.py
print "hi"
a = [1,2,3]
for e in a:
print e
print "bye"
import readline
readline.write_history_file('history.py')
到目前为止,是否有一种快速、方便的方法将所有代码输入 python 解释器?例如,如果我在解释器中输入:
Steven$ python
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hi"
hi
>>> a = [1,2,3]
>>> for e in a:
... print e
...
1
2
3
>>> print "bye"
bye
>>>
我想得到这些行:
print "hi"
a = [1,2,3]
for e in a:
print e
print "bye"
%history 魔法函数应该为您完成。
In [1]: l = [1,2,3]
In [2]: %history
l = [1,2,3]
%history
如果您发现自己经常这样做,请考虑使用 ipython notebook.
您可以使用 readline
模块。
Python 2.7.5 (default, Nov 3 2014, 14:26:24)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hi"
hi
>>> a = [1,2,3]
>>> for e in a:
... print e
...
1
2
3
>>> print "bye"
bye
>>> import readline
>>> readline.write_history_file('history.py')
文件 history.py
将包含您的历史记录,包括最后两行:
$ cat history.py print "hi" a = [1,2,3] for e in a: print e print "bye" import readline readline.write_history_file('history.py')