Search code examples
pythonunixhaskellpipetee

How to capture prompts in stdout/stderr?


I'm trying to record a user's terminal session in a log file; fairly simply, I made a Python wrapper for ghci (interactive Haskell) that looks like:

#!/usr/bin/env python

import os

cmd = 'ghci 2>&1 | tee hs.log'
os.system(cmd)

However, this only captures what is printed back to the user, and not the prompts/what the user has typed in. So if the session looks like:

$ ghci 2>$1 | tee hs.log
GHCi, version 7.10.3: http://www.haskell.org/ghc/  :? for help
Prelude> 1+2
3
Prelude> 3+4
7
Prelude>

hs.log only has:

$ cat hs.log
GHCi, version 7.10.3: http://www.haskell.org/ghc/  :? for help
3
7

How do you capture both the output and the input during an interactive terminal session?


Solution

  • You can use the script command to capture both input and output.

    cmd = 'script hs.log ghci'
    

    Note that this captures all the raw input and output from the terminal. You'll see all the user's editing, and if the program is full-screen you'll see all its escape sequences to move the cursor around. See the linked documentation for full details.