Skip to content

Instantly share code, notes, and snippets.

@burgil
Last active March 26, 2024 20:23
Show Gist options
  • Save burgil/e5957d9f672e3eec931498baf3ef06fe to your computer and use it in GitHub Desktop.
Save burgil/e5957d9f672e3eec931498baf3ef06fe to your computer and use it in GitHub Desktop.
Super Simple Simulated Linux Terminal for Python with support for cat, ls, cd and exit commands - Enjoy!
class Terminal:
def __init__(self):
self.root = {
"": {
"directories": ["Documents", "Downloads"],
"files": []
},
"Documents": {
"directories": [],
"files": {
"document1.txt": "This is the content of document1.",
"document2.txt": "This is the content of document2."
}
},
"Downloads": {
"directories": ["Images", "Videos"],
"files": {
"download1.txt": "This is the content of download1.",
"download2.txt": "This is the content of download2."
}
},
"Images": {
"directories": [],
"files": {
"image1.jpg": "Binary content of image1.jpg",
"image2.jpg": "Binary content of image2.jpg"
}
},
"Videos": {
"directories": [],
"files": {
"video1.mp4": "Binary content of video1.mp4",
"video2.mp4": "Binary content of video2.mp4"
}
}
}
self.current_directory = ""
def ls(self):
directories = self.root[self.current_directory.lstrip("/")]["directories"]
files = self.root[self.current_directory.lstrip("/")]["files"]
print("Directories:")
for directory in directories:
print(directory + "/")
print("Files:")
for file in files:
print(file)
def cat(self, filename):
files = self.root[self.current_directory.lstrip("/")]["files"]
if filename in files:
print(f"Contents of {filename}:")
print(files[filename])
else:
print(f"File '{filename}' not found.")
def cd(self, directory):
full_path = self.current_directory + "/" + directory
if full_path.lstrip("/") in self.root:
self.current_directory = full_path
print(f"Changed directory to: {self.current_directory}")
else:
print(f"Directory '{directory}' not found.")
def run(self):
while True:
command = input(f"{self.current_directory}> ").split()
if not command:
continue # ask again if no command entered
cmd = command[0]
if cmd == "ls":
self.ls()
elif cmd == "cat":
if len(command) > 1:
self.cat(command[1])
else:
print("Usage: cat <filename>")
elif cmd == "cd":
if len(command) > 1:
self.cd(command[1])
else:
print("Usage: cd <directory>")
elif cmd == "exit":
print("Exiting terminal.")
break
else:
print("Command not found.")
if __name__ == "__main__":
terminal = Terminal()
terminal.run()
@burgil
Copy link
Author

burgil commented Mar 26, 2024

Preview

image

@burgil
Copy link
Author

burgil commented Mar 26, 2024

TODO:

  1. Add support for going back one directory with cd ..
  2. Add support for sub directories
  3. Add a command to edit the text? nano
  4. Make the terminal look more like linux

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment