Last active
January 10, 2025 23:36
-
-
Save gual/6b3070b81d7cae32049046c85b8b79f5 to your computer and use it in GitHub Desktop.
CodeCrafters Shell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import subprocess | |
import sys | |
commands = ["echo", "exit", "quit", "type"] | |
command_path_cache = {} | |
def run_exit(input_values): | |
try: | |
if input_values[1]: | |
i = int(input_values[1]) | |
if i >= 0 and i <= 255: | |
return i | |
else: | |
return None | |
except: | |
return None | |
# > the value shall be the exit value of the last command | |
# executed, or zero if no command was executed. | |
return 0 | |
def run_echo(input_values): | |
[sys.stdout.write(f"{i} ") for i in input_values[1:]] | |
sys.stdout.write("\n") | |
def run_type(input_values): | |
arg = input_values[1] | |
if arg in commands: | |
sys.stdout.write(f"{arg} is a shell builtin\n") | |
return 0 | |
command_path = get_command_path(arg) | |
if command_path: | |
sys.stdout.write(f"{arg} is {command_path}/{arg}\n") | |
return 0 | |
sys.stdout.write(f"{arg}: not found\n") | |
return 1 | |
def get_command_path(command): | |
if command in command_path_cache: | |
return command_path_cache[command] | |
for path in os.environ["PATH"].split(sep=":"): | |
if os.path.exists(path) and command in os.listdir(path): | |
command_path_cache[command] = path | |
return path | |
command_path_cache[command] = None | |
return None | |
def main(): | |
while True: | |
sys.stdout.write("$ ") | |
input_values = input().split() | |
command = input_values[0] | |
if command == ("exit" or "quit"): | |
return run_exit(input_values) | |
elif command == "echo": | |
run_echo(input_values) | |
elif command == "type": | |
run_type(input_values) | |
else: | |
if get_command_path(command): | |
sys.stdout.write(subprocess.run(input_values, capture_output=True).stdout.decode('utf-8')) | |
else: | |
sys.stdout.write(f"{command}: command not found\n") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment