Log IPython output?

2019-02-16 16:05发布

Is there any way to make IPython's logging capability include output as well as input?

This is what a log file looks like currently:

#!/usr/bin/env python 
# 2012-08-06.py 
# IPython automatic logging file
# 12:02 
# =================================
print "test"

I'd like to have one more line show up:

#!/usr/bin/env python 
# 2012-08-06.py 
# IPython automatic logging file
# 12:02 
# =================================
print "test"
# test

(the # is because I assume that is needed to prevent breaking IPython's logplay feature)

I suppose this is possible using IPython notebooks, but on at least one machine I need this for, I'm limited to ipython 0.10.2.

EDIT: I'd like to know how to set this up automatically, i.e. within the configuration file. Right now my config looks like

from time import strftime
import os
logfilename = strftime('ipython_log_%Y-%m-%d')+".py" 
logfilepath = "%s/%s" % (os.getcwd(),logfilename) 

file_handle = open(logfilepath,'a') 
file_handle.write('########################################################\n') 
out_str = '# Started Logging At: '+ strftime('%Y-%m-%d %H:%M:%S\n') 
file_handle.write(out_str) 
file_handle.write('########################################################\n') 
file_handle.close() 

c.TerminalInteractiveShell.logappend = logfilepath
c.TerminalInteractiveShell.logstart = True

but specifying c.TerminalInteractiveShell.log_output = True seems to have no affect

标签: ipython
1条回答
走好不送
2楼-- · 2019-02-16 16:37

There's the -o option for %logstart:

-o: log also IPython's output.  In this mode, all commands which
  generate an Out[NN] prompt are recorded to the logfile, right after
  their corresponding input line.  The output lines are always
  prepended with a '#[Out]# ' marker, so that the log remains valid
  Python code.

ADDENDUM: If you are in an interactive ipython session for which logging has already been started, you must first stop logging and then restart:

In [1]: %logstop

In [2]: %logstart -o
Activating auto-logging. Current session state plus future input saved.
Filename       : ./ipython.py
Mode           : backup
Output logging : True
Raw input log  : False
Timestamping   : False
State          : active

Observe that, after the restart, "Output Logging" is now "True".

查看更多
登录 后发表回答