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
- Open your terminal (or command prompt).
- Navigate to the directory where you saved
custom_shell.py
. - Run the script using the command:bashCopy code
python custom_shell.py
How It Works
- Command Input: The shell prompts you to enter a command.
- Command Processing:
- Exit Command: You can type
exit
orquit
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.
- Exit Command: You can type
- Error Handling: The shell handles errors gracefully, providing feedback if a command fails.
Example Usage
- Change Directory: Type
cd path/to/directory
to navigate to a different directory. - Execute Commands: Type commands like
ls
(ordir
on Windows) to list files, orecho Hello World
to print a message. - Exit: Type
exit
orquit
to close the shell.
Leave a Reply