Custom Shell

Create the Shell

Create a file named custom_shell.py and add the following code:

pythonCopy codeimport os
import subprocess

class CustomShell:
    def __init__(self):
        self.running = True

    def run(self):
        while self.running:
            try:
                command = input(f"{os.getcwd()}$ ").strip()
                self.process_command(command)
            except KeyboardInterrupt:
                print("\nExiting the shell.")
                self.running = False

    def process_command(self, command):
        if command.lower() in ['exit', 'quit']:
            self.running = False
            return
        elif command.startswith('cd '):
            self.change_directory(command[3:])
        else:
            self.execute_command(command)

    def change_directory(self, path):
        try:
            os.chdir(path)
            print(f"Changed directory to {os.getcwd()}")
        except Exception as e:
            print(f"cd: {e}")

    def execute_command(self, command):
        try:
            # Execute the command
            result = subprocess.run(command, shell=True, check=True, text=True, capture_output=True)
            print(result.stdout)
        except subprocess.CalledProcessError as e:
            print(f"Error: {e.stderr.strip()}")

if __name__ == "__main__":
    shell = CustomShell()
    shell.run()

Step 2: Running the Custom Shell

  1. Open your terminal (or command prompt).
  2. Navigate to the directory where you saved custom_shell.py.
  3. Run the script using the command:bashCopy codepython custom_shell.py

How It Works

  • Command Input: The shell prompts you to enter a command.
  • Command Processing:
    • Exit Command: You can type exit or quit to exit the shell.
    • Change Directory: Use cd <directory> to change the current working directory.
    • Execute Command: Any other command is executed using the subprocess module.
  • Error Handling: The shell handles errors gracefully, providing feedback if a command fails.

Example Usage

  1. Change Directory: Type cd path/to/directory to navigate to a different directory.
  2. Execute Commands: Type commands like ls (or dir on Windows) to list files, or echo Hello World to print a message.
  3. Exit: Type exit or quit to close the shell.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *