0

I want to store the commands and their output to be stored in log.txt . So, i am assigning customer Logger class object to sys.stdout with write method overriden to store the output both in file as well as to print in console. The problem here is that when sys.stdout is overriden, 'tab' autocompletion of commands in ABC class ( hi,hello,shutdown ) is not working and up and down arrows are also not working for forward and backward history commands.

import cmd
import sys
import readline
LOG_FILE=open("log.txt",'w+')
class Logger():
    def __init__(self):
        self.console=sys.stdout
    def write(self,message):
        self.console.write(message)
        LOG_FILE.write(message)
    def flush(self):
        self.console.flush()

class ABC(cmd.Cmd):
    def __init__(self):
        sys.stdout = Logger()
        readline.set_completer(self.complete)
        readline.parse_and_bind("tab: complete")
    def do_hello(self,args):
        print("hello entered")
    def do_hi(self,args):
        print("Hi entered")
    def do_shutdown(self,args):
        print("shutting down")
        global LOG_FILE
        LOG_FILE.close()
    #sys.exit()
    def emptyline(self):
        pass
    def precmd(self,args):
        LOG_FILE.write(args+"\n")

if __name__ == '__main__':
    ABC().cmdloop()

cmd line image

I expect that when 'hel' is typed in command above and then if tab is pressed, it should display 'hello help' in the next line. Pressing tab shouldn't add 4 spaces to the command being typed. Pleas help with working solution in which auto completion of commands with tab,up/down arrow works and the commands and their output should store in a file 'log.txt'. Please mind that i am running this program in red had linux 7 OS, not windows.

Sekhar
  • 1
  • 2

0 Answers0