pythonpython-cmd

How to implement clear in cmd.Cmd?


I am working on a custom command line interpreter, and I want to implement the 'clear' command, just like the the one in bash shell. Is there any way to do that?

I have attempted it but I don't think it is correct at all:

#!/usr/bin/python3
import cmd
import sys
import os


class HBNBCommand(cmd.Cmd):
    """Command line interpreter"""

    def do_clear(self):
        """Clear command similar to clear from shell"""
        os.system('clear')


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

When I try it, it gives me the exception:

Traceback (most recent call last):
  File "/home/leuel/PycharmProjects/AirBnB_clone/./console.py", line 22, in <module>
    HBNBCommand().cmdloop()
  File "/usr/lib/python3.10/cmd.py", line 138, in cmdloop
    stop = self.onecmd(line)
  File "/usr/lib/python3.10/cmd.py", line 217, in onecmd
    return func(arg)
TypeError: HBNBCommand.do_clear() takes 1 positional argument but 2 were given

Solution

  • When inheriting from cmd to build your custom shell, methods expect at least one argument. To quote from this resource, "The interpreter uses a loop to read all lines from its input, parse them, and then dispatch the command to an appropriate command handler. Input lines are parsed into two parts. The command, and any other text on the line."

    Since do_clear has not provided for an argument, the command cannot handle any additional input, even when that input does not exist.

    class HBNBCommand(cmd.Cmd):
        """Command line interpreter"""
    
        def do_clear(self, arg):
            """Clear command similar to clear from shell"""
            os.system('clear')
    
    
    if __name__ == '__main__':
        HBNBCommand().cmdloop()
    

    You can also refer to the Cmd example in the Python docs: https://docs.python.org/3/library/cmd.html#cmd-example