neongm

nc

Oct 16th, 2019
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.80 KB | None | 0 0
  1. # попытка создать свою консоль с блекджеком и удобными командами
  2. # TODO: help, os.mkdir(path, mode=0o777, *, dir_fd=None)
  3. # os.path.abspath() - преобразование относительного пути в абсолютный
  4. # os.path.isabs() — возвращает True, если путь абсолютный               --------------
  5. import os
  6.  
  7.  
  8. def commandsRecognizer(inp):
  9.     if inp[0] == 'cd':
  10.         cd(inp)
  11.     elif inp[0] == 'sysinfo':
  12.         sysinfo()
  13.     elif inp[0] == 'dir':
  14.         dir()
  15.     elif inp[0] == 'cdir':
  16.         createDirectory(inp)
  17.     elif inp[0] == 'rdir':
  18.         removeDirectory(inp)
  19.     elif inp[0] == 'open':
  20.         openFile(inp)
  21.     elif inp[0] == 'cfile':
  22.         createFile(inp)
  23.     elif inp[0] == 'rfile':
  24.         removeFile(inp)
  25.     elif inp[0] == 'cmd':
  26.         systemCmd(inp)
  27.  
  28.  
  29. def systemCmd(inp):
  30.     #try:
  31.         inp = ' '.join(inp[1::])
  32.         out = str(os.system(inp)).encode("1251", errors='ignore')
  33.         print(out)
  34.     #except: print('опять ты что-то сломал')
  35.  
  36. def sysinfo():
  37.     print(os.name)
  38.  
  39.  
  40. def cd(inp):
  41.     try:
  42.         td = os.getcwd().split('\\')  # разделяй и властвуй, директорию на список
  43.         if '-' in inp[1]:
  44.             s = inp[1].count('-')                     # кол-во отступов назад
  45.             if s >= len(td): s = len(td)-2        # если слишком много минусов - в предпоследнюю
  46.             for i in range(s):            # убираем элементы списка и соединяем его в строку через \
  47.                 del td[-1]
  48.             td = '\\'.join(td)
  49.             os.chdir(td)                              # меняем директорию на новую
  50.  
  51.         elif 'C:' not in inp[1]:
  52.             td.append(inp[1])
  53.             td = '\\'.join(td)
  54.             os.chdir(td)
  55.     except:
  56.         print('что-то пошло не так')
  57.  
  58.  
  59. def dir():
  60.     for i in os.listdir(os.getcwd()):
  61.         if os.path.isfile(i):
  62.             print(i,'  ', round(os.path.getsize(i)/1024,4),'KB')
  63.         else: print(i)
  64.     if os.listdir(os.getcwd())==[]:
  65.         print('directory is empty')
  66.  
  67.  
  68. def createDirectory(inp):
  69.     try:
  70.         os.mkdir(os.getcwd()+'\\'+inp[1])
  71.         print('created', inp[1])
  72.     except: print('command syntax error')
  73.  
  74.  
  75. def removeDirectory(inp):
  76.     try:
  77.         os.rmdir(os.path.abspath(inp[1]))
  78.         print('removed', inp[1])
  79.     except: print('directory not found or folder are not empty')
  80.  
  81.  
  82. def openFile(inp):
  83.     try:
  84.         os.startfile(str(inp[1]))
  85.         print('opening', inp[1])
  86.     except: print('file not found')
  87.  
  88.  
  89. def remove(inp):
  90.     try:
  91.         os.remove(str(inp[1]))
  92.         print('removed', inp[1])
  93.     except: print('file not found')
  94.  
  95.  
  96. def createFile(inp):
  97.     try:
  98.         nf = open(inp[1], "w+")
  99.         nf.close()
  100.     except: print('command syntax error')
  101.  
  102.  
  103. def cin():                                        # Console input, разделяет ввод
  104.     print(os.getcwd(), end='  ')                  # на список для более удобной работы
  105.     inp = input().split()
  106.     if inp[0] == 'stop': return(True)
  107.     if inp[0] not in commandsList:                # проверка наличия команды
  108.         print("unknown command")
  109.     commandsRecognizer(inp)                       # если есть - узнать какая и запустить функцию
  110.  
  111.  
  112. commandsList = ['stop','cd','sysinfo','dir', 'cdir', 'rdir', 'open', 'cfile', 'rfile', 'cmd']
  113. #список команд, надо как-то с help сопоставить, TODO, mb словарём сделать
  114.  
  115. while True:
  116.     if cin(): break
Advertisement
Add Comment
Please, Sign In to add comment