I would like to have real-time access to the input and error of the interpreter, as well as to standard outputs. Preferably, this information will be written to a file so that I can query the file for changes after the entire interpreter command has been entered. For example, given an interpreter session:
>>> 5 * 7 35 >>> print("Hello, world!") Hello, world! >>> "Hello, world!" 'Hello, world!'
I want to see the following in a log file:
> 5 * 7 35 > print("Hello, world!") Hello, world! > "Hello, world!" 'Hello, world!'
Formatting is not important; The important thing is that I can search for a file for keywords to trigger interactive events during a session.
What I have learned so far is trying to do this:
The Python code module allows me to create an InteractiveConsole object, the raw_input method, which I can override to enter a file, for example:
import code class LoggedConsole(code.InteractiveConsole): def __init__(self, locals): super(LoggedConsole, self).__init__(locals) self.file = open('consolelog.dat', 'a') def __del__(self): self.file.close() def raw_input(self, prompt=""): data = input(prompt) self.file.write(data+'\n') return data
In addition, InteractiveConsole uses the built-in write method to register errors, which I can override to:
def write(self, data): sys.stderr.write(data) self.file.write(data+'\n')
I also found out that the following snippet will write all stdout:
class Tee(object): def __init__(self): self.file = open('consolelog.dat', 'a') self.stdout = sys.stdout def __del__(self): sys.stdout = self.stdout self.file.close() def write(self, data): self.file.write(data) self.stdout.write(data) sys.stdout = Tee()
My (broken) attempt to combine all of this was to then create a LoggedConsole object and pass it Tee to locals.
console = LoggedConsole(locals={sys.stdout:LoggedExec()}) console.interact()
(I have not met local residents before, so maybe I am doing it wrong here, but I am not getting an error message.)
In any case, this will open a new interactive console and will log (after closing) all input and errors, but not output. For a moment I hit my head about it, and it seems to me that I'm close, but maybe not even.
Also, is there a way for all this to happen during the session? Currently, all logging occurs after the session is closed.
Thank you for your time, sorry for the wall of text.
edit: I would like to be able to accomplish this in a standard Python interpreter for portability purposes.
edit2: Jaime snippet works great for registering everything I need. In any case, what can I get him to do this in real time, rather than wait for the session to close?
Edit3: Figured it out :). Final working fragment:
import code import sys class Tee(object): def __init__(self, log_fname, mode='a'): self.log = open(log_fname, mode) def __del__(self):