3 """This spawns a sub-shell (bash) and gives the user interactive control. The
4 entire shell session is logged to a file called script.log. This behaves much
5 like the classic BSD command 'script'.
7 ./script.py [-a] [-c command] {logfilename}
9 logfilename : This is the name of the log file. Default is script.log.
10 -a : Append to log file. Default is to overwrite log file.
11 -c : spawn command. Default is to spawn the sh shell.
15 This will start a bash shell and append to the log named my_session.log:
17 ./script.py -a -c bash my_session.log
21 import os, sys, time, getopt
22 import signal, fcntl, termios, struct
26 global_pexpect_instance = None # Used by signal handler
28 def exit_with_usage():
30 print globals()['__doc__']
35 ######################################################################
36 # Parse the options, arguments, get ready, etc.
37 ######################################################################
39 optlist, args = getopt.getopt(sys.argv[1:], 'h?ac:', ['help','h','?'])
43 options = dict(optlist)
47 if [elem for elem in options if elem in ['-h','--h','-?','--?','--help']]:
52 script_filename = args[0]
54 script_filename = "script.log"
56 fout = file (script_filename, "ab")
58 fout = file (script_filename, "wb")
60 command = options['-c']
64 # Begin log with date/time in the form CCCCyymm.hhmmss
65 fout.write ('# %4d%02d%02d.%02d%02d%02d \n' % time.localtime()[:-3])
67 ######################################################################
68 # Start the interactive session
69 ######################################################################
70 p = pexpect.spawn(command)
72 global global_pexpect_instance
73 global_pexpect_instance = p
74 signal.signal(signal.SIGWINCH, sigwinch_passthrough)
76 print "Script recording started. Type ^] (ASCII 29) to escape from the script shell."
81 def sigwinch_passthrough (sig, data):
83 # Check for buggy platforms (see pexpect.setwinsize()).
84 if 'TIOCGWINSZ' in dir(termios):
85 TIOCGWINSZ = termios.TIOCGWINSZ
87 TIOCGWINSZ = 1074295912 # assume
88 s = struct.pack ("HHHH", 0, 0, 0, 0)
89 a = struct.unpack ('HHHH', fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ , s))
90 global global_pexpect_instance
91 global_pexpect_instance.setwinsize(a[0],a[1])
93 if __name__ == "__main__":
101 traceback.print_exc()