BrinkerVII

cmd.py

Feb 12th, 2020
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.62 KB | None | 0 0
  1. import os
  2. import subprocess
  3. import sys
  4.  
  5. DELIMITER = " "
  6. HOME = os.environ[list(filter(lambda k: k.lower() == "userprofile", os.environ.keys()))[0]]
  7. os.environ["HOME"] = HOME
  8.  
  9. os.chdir(HOME)
  10.  
  11.  
  12. class State:
  13.     running = True
  14.  
  15.  
  16. def cwd_name():
  17.     cwd = os.getcwd()
  18.     if cwd == os.environ["HOME"]:
  19.         return "~"
  20.  
  21.     return os.path.basename(cwd)
  22.  
  23.  
  24. def cmd_exit():
  25.     State.running = False
  26.     print("Goodbye")
  27.  
  28.  
  29. def cmd_pwd():
  30.     print(os.path.abspath(os.getcwd()))
  31.  
  32.  
  33. def cmd_ls():
  34.     cwd = os.path.abspath(os.getcwd())
  35.     print(f"Listing the contents of {cwd}\n")
  36.  
  37.     listing = os.listdir(cwd)
  38.  
  39.     if len(listing) > 0:
  40.         for file in listing:
  41.             path = os.path.join(cwd, file)
  42.             stat = os.stat(path)
  43.  
  44.             type_str = "?"
  45.             if os.path.isfile(path):
  46.                 type_str = "f"
  47.  
  48.             elif os.path.isdir(path):
  49.                 type_str = "d"
  50.  
  51.             print(f"{type_str} {file if len(file) < 60 else file[:57] + '...'} ({stat.st_size / 1024 / 1024} MiB)")
  52.  
  53.     else:
  54.         print("Directory is empty!", file=sys.stderr)
  55.  
  56.  
  57. def cmd_cd(target):
  58.     cwd = os.path.abspath(os.getcwd())
  59.     target_path = os.path.join(cwd, target)
  60.     target_path = os.path.abspath(target_path)
  61.  
  62.     if os.path.exists(target_path):
  63.         os.chdir(target_path)
  64.         return
  65.  
  66.     possible_targets = list(filter(lambda path: path.startswith(target), os.listdir(cwd)))
  67.  
  68.     if len(possible_targets) > 1:
  69.         print(f"Multiple possible targets to cd into:{str(possible_targets)}", file=sys.stderr)
  70.         return
  71.  
  72.     if len(possible_targets) == 1:
  73.         cmd_cd(possible_targets[0])
  74.         return
  75.  
  76.     print(f"Could not cd to {target}, it does not exist!", file=sys.stderr)
  77.  
  78.  
  79. def cmd_cat(*files):
  80.     output = []
  81.     for file in files:
  82.         path = os.path.join(os.path.abspath(os.getcwd()), file)
  83.  
  84.         with open(path, "rb") as fp:
  85.             output.append(fp.read().decode("UTF-8"))
  86.  
  87.     print("".join(output))
  88.  
  89.  
  90. BUILTIN_COMMANDS = {
  91.     "exit": cmd_exit,
  92.     "pwd": cmd_pwd,
  93.     "ls": cmd_ls,
  94.     "dir": cmd_ls,
  95.     "cd": cmd_cd,
  96.     "cat": cmd_cat
  97. }
  98.  
  99. while State.running:
  100.     prompt = f"{cwd_name()} -> "
  101.     command = input(prompt).split(DELIMITER)
  102.     command, arguments = command[0], command[1:]
  103.  
  104.     if not command:
  105.         continue
  106.  
  107.     else:
  108.         try:
  109.             if command in BUILTIN_COMMANDS:
  110.                 BUILTIN_COMMANDS[command](*arguments)
  111.  
  112.             else:
  113.                 subprocess.check_call([command, *arguments])
  114.  
  115.         except Exception as e:
  116.             print(e, file=sys.stderr)
Advertisement
Add Comment
Please, Sign In to add comment