Last active
June 12, 2018 03:16
-
-
Save danthedaniel/21dcf2be5d806bddb54f7f0391d79ec4 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3 | |
import re | |
import sys | |
import os | |
import signal | |
from typing import List | |
from subprocess import call | |
BUILTINS = { | |
"cd": lambda path, *_args: os.chdir(path), | |
"pwd": lambda *_args: print(os.getcwd()), | |
"help": lambda *_args: print("commands:\n" + "\t".join(BUILTINS.keys())) | |
} | |
def sigint_handler(_signo, _stack_frame): | |
print() | |
sys.exit(0) | |
def try_builtin(tokens: List[str]) -> bool: | |
"""Try to execute tokens as a builtin.""" | |
try: | |
BUILTINS[tokens[0]](*tokens[1:]) | |
return True | |
except KeyError: | |
return False | |
def try_command(tokens: List[str]) -> bool: | |
"""Try to execute tokens as a command.""" | |
try: | |
status = call(tokens, stdout=sys.stdout, stderr=sys.stderr) | |
return True | |
except FileNotFoundError as e: | |
print(f"{e.filename}: command not found", file=sys.stderr) | |
return False | |
def main() -> None: | |
"""Python Shell.""" | |
signal.signal(signal.SIGINT, sigint_handler) | |
while True: | |
try: | |
command = input(f"{os.getcwd()}$ ") | |
except EOFError: | |
print() | |
sys.exit(0) | |
tokens = re.findall(r"\S+", command) | |
if len(tokens) == 0: | |
continue | |
try_builtin(tokens) or try_command(tokens) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment