Advertisement
BERKYT

A simple bash emulator

Sep 21st, 2023 (edited)
1,158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.14 KB | Software | 0 0
  1. import os
  2. import getpass
  3.  
  4.  
  5. class GlobalPath:
  6.     SELF_PATH = __file__[:__file__.rfind('\\')]
  7.     visible_path = ''
  8.  
  9.  
  10. def ls(path: str = 'DEFAULT') -> str:
  11.     if path != 'DEFAULT':
  12.         files = os.listdir(path)
  13.     else:
  14.         files = os.listdir(GlobalPath.SELF_PATH)
  15.  
  16.     res = ''
  17.  
  18.     for offset, file in enumerate(files):
  19.         res += file + '\t'
  20.  
  21.         if offset % 6 == 0 and offset != 0:
  22.             res += '\n'
  23.  
  24.     return res
  25.  
  26.  
  27. def cat(*files) -> str:
  28.     res = ''
  29.  
  30.     for file in files:
  31.         with open(file=f'{GlobalPath.SELF_PATH}\\{file}', mode='r', encoding='utf-8') as f:
  32.             for line in f:
  33.                 res += line
  34.  
  35.     return res
  36.  
  37.  
  38. def pwd() -> str:
  39.     return GlobalPath.SELF_PATH
  40.  
  41.  
  42. def cd(path: str):
  43.     if path == '..':
  44.         GlobalPath.SELF_PATH = generate_new_path(GlobalPath.SELF_PATH)
  45.  
  46.         path = generate_new_path(GlobalPath.visible_path).replace('\\\\', '')
  47.  
  48.         GlobalPath.visible_path = path
  49.     else:
  50.         if os.path.exists(GlobalPath.SELF_PATH + f'\\{path}'):
  51.             GlobalPath.SELF_PATH += f'\\{path}'
  52.             GlobalPath.visible_path += f'\\{path}'
  53.  
  54.  
  55. def convert_path_to_list(visible_path: str) -> list:
  56.     return visible_path.split('\\')
  57.  
  58.  
  59. def generate_new_path(path):
  60.     tmp = convert_path_to_list(path)
  61.     tmp.pop()
  62.  
  63.     path = ''
  64.  
  65.     for offset, file in enumerate(tmp):
  66.         if offset != 0:
  67.             path += f'\\{file}'
  68.         else:
  69.             path += f'{file}'
  70.  
  71.     return path
  72.  
  73.  
  74. def run():
  75.     commands = {
  76.         'ls': ls,
  77.         'cat': cat,
  78.         'pwd': pwd,
  79.         'cd': cd,
  80.     }
  81.  
  82.     while True:
  83.         user_name = f'{getpass.getuser()}@ubuntu:{GlobalPath.visible_path if GlobalPath.visible_path else "~"}$ '
  84.         enter_command = input(user_name).split(' ')
  85.         command, args = enter_command[0], enter_command[1:]
  86.  
  87.         if not commands.get(command):
  88.             continue
  89.  
  90.         try:
  91.             res = commands[command](*args)
  92.         except Exception as e:
  93.             print(e)
  94.             continue
  95.  
  96.         if res:
  97.             print(res)
  98.  
  99.  
  100. if __name__ == '__main__':
  101.     run()
  102.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement