好吧,通常要完成它,你必须重写 pythonprint
内置功能。但是...有ipython,它提供了一些钩子。
首先你需要有ipython
安装:
#bash
sudo pip install ipython
(我使用 sudo 来简单地找到我需要访问的文件夹,进一步阅读)
安装 ipython 后,您将拥有可用的 ipython 扩展文件夹,因此请使用它:
#bash
cd ~/.ipython/extensions/
并在那里创建一个名为print_to_file.py
,这是它的内容:
#python
class PrintWatcher(object):
def __init__(self, ip):
self.shell = ip
def post_execute(self):
with open('/home/turkus/shell.txt', 'a+') as f:
in_len = len(self.shell.user_ns['In'])
i = in_len - 1
in_ = self.shell.user_ns['In'][i]
out = self.shell.user_ns['Out'].get(i, '')
# you can edit this line if you want different input in shell.txt
f.write('{}\n{}\n'.format(in_, out))
def load_ipython_extension(ip):
pw = PrintWatcher(ip)
ip.events.register('post_run_cell', pw.post_execute)
保存文件后只需运行:
#bash
ipython profile create
# you will get something like that:
[ProfileCreate] Generating default config file: u'/home/turkus/.ipython/profile_default/ipython_config.py'
现在回到设置我们的钩子。我们必须打开ipython_config.py
在上面的路径下创建并放一些魔法(那里有很多东西,所以转到文件末尾):
# some commented lines here
c = get_config()
c.InteractiveShellApp.extensions = [
'print_to_file'
]
保存后就可以运行了ipython
并编写你的代码。您的每个输入都将写入您上面提供的路径下的文件中,在我的例子中是:
/home/turkus/shell.txt
Notes
您可以避免每次都加载扩展程序ipython
只需删除即可启动'print_to_file'
from c.InteractiveShellApp.extensions
列出在ipython_config.py
。但请记住,您可以随时加载它,只需输入ipython
安慰:
➜ ~ ipython
Python 2.7.12 (default, Jul 1 2016, 15:12:24)
Type "copyright", "credits" or "license" for more information.
IPython 4.0.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: %load_ext print_to_file
任何变化print_to_file.py
使用后会反映在打开的ipython shell中%reload_ext print_to_file
命令,因此您不必退出并再次启动它。