Parcourir la source

Merge branch 'master' of https://tj.kbsu.ru/AlexSidorov/InformationCollector

AlexSidorov il y a 1 an
Parent
commit
d95ca80e8f
1 fichiers modifiés avec 29 ajouts et 55 suppressions
  1. 29 55
      main.py

+ 29 - 55
main.py

@@ -4,6 +4,7 @@ import sys
 import argparse
 from logger import *
 from datetime import datetime
+import pandas as pd
 
 ARGS = None
 
@@ -12,9 +13,7 @@ parse = argparse.ArgumentParser(
     
 parse.add_argument('-p', '--path', help='Указать в какой директории искать',
                    default=os.path.dirname(sys.argv[0]))
-parse.add_argument('-e', '--encoding',
-                   help='Указать в какой кодировке сохранять', default='ANSI')
-parse.add_argument('-s', '--open_encoding',
+parse.add_argument('-e', '--open_encoding',
                    help='Указать в какой кодировке открывать', default='utf-16')
 parse.add_argument('-d', '--delimiter', help='разделитель csv', default=',')
 
@@ -46,20 +45,8 @@ class ObjectReady:
     def get_len_dict(self) -> int:
         return len(self.__dict__)
 
-    def get_csv_row(self) -> str:
-        if self.get_len_dict() < 11:
-            return F"{ARGS.delimiter}".join((self.frame, self.cabinet))
-
-        try:
-            row_interface = F"{ARGS.delimiter}".join(
-                [ARGS.delimiter.join(
-                    (self.__dict__.get(F"ip{i}"), self.__dict__.get(F"mac{i}")
-                )
-            ) for i in range(self.count_interface)])
-
-            return ARGS.delimiter.join((self.frame, self.cabinet, self.os, self.motherboard, self.cpu, self.ram, row_interface))
-        except AttributeError:
-            return None
+    def get_row(self) -> str:
+        return self.__dict__
 
 
 def get_paths() -> list:
@@ -75,19 +62,18 @@ def convert_mb_to_gb(val: str) -> str:
     return str(round(numbers/1024, 1))+' GB'
 
 
-def get_ser_motherboard(row: str) -> str:
-    if len(row) > 0:
-        if row[6] not in ['To be filled by O.E.M.', 'Default string']:
-            return row[6]
-        else:
-            return None
-    else:
-        return None
+def get_ser_motherboard(row: list) -> str:
+    try:
+        return row if row not in ['To be filled by O.E.M.', 'Default string'] else None
+    except IndexError:
+        pass
 
 
 def get_data_from_file(path: str, obj: ObjectReady) -> None:
     global COUNT_INTERFACE
-    with open(path, 'r', encoding=ARGS.open_encoding) as file:
+    
+    with open(path, 'r', encoding=args.open_encoding) as file:
+        
         cs = csv.reader(file, delimiter=',')
 
         next(cs)
@@ -95,18 +81,18 @@ def get_data_from_file(path: str, obj: ObjectReady) -> None:
         obj.os = line_info_computers[7]
         obj.cpu = line_info_computers[13]
         obj.ram = convert_mb_to_gb(line_info_computers[14])
-
-        obj.ip1 = None
-        obj.mac1 = None
-
+        obj.motherboard = None
+        obj.count_interface = 0
         count_interface = 0
-        for x in cs:
-            if x[0] == '6200':
-                obj.motherboard = get_ser_motherboard(x)
-
-            if x[0] == '2600' and len(x) > 2 and check_correct_controller(x[3]):
-                setattr(obj, F'ip{count_interface}', x[6].split(' ')[0])
-                setattr(obj, F'mac{count_interface}', x[-3])
+        
+        for line in cs:
+            data = list(pd.Series(line))
+            if data[0] == '6200':
+                obj.motherboard = get_ser_motherboard(data[6])
+
+            if data[0] == '2600' and len(data) > 2 and check_correct_controller(data[3]):
+                setattr(obj, F'ip{count_interface+1}', data[6].split(' ')[0])
+                setattr(obj, F'mac{count_interface+1}', data[-3])
                 count_interface += 1
 
         # Увеличиваем значение если количестов интерфейсов больше в этой строке
@@ -120,7 +106,7 @@ def get_data_from_file(path: str, obj: ObjectReady) -> None:
 def get_ready_information() -> list[ObjectReady]:
     list_objects = []
     for path in get_paths():
-
+        
         obj = ObjectReady()
         obj.frame = os.path.basename(os.path.dirname(path))
         obj.path = path
@@ -153,23 +139,11 @@ def create_header_interface() -> str:
 
 
 def create_csv(list_obj: list[ObjectReady]) -> None:
-    namefile = F"result-{datetime.today().strftime('%Y-%m-%d-%H.%M.%S')}"
-
-    with open(F"{namefile}.csv", 'w', newline='', encoding=ARGS.encoding) as f:
-        header_interface = create_header_interface()
-        header_csv = ARGS.delimiter.join(
-            ("frame", "cabinet", "os", "motherboard", "cpu", "ram", header_interface))
-
-        f.write(header_csv + "\n")
-
-        for obj in list_obj:
-            try:
-                f.write(obj.get_csv_row() + '\n')
-            except TypeError as te:
-                logger.error(F'{obj.path} -> {te}')
-                continue
-
-
+    namefile = F"result-{datetime.today().strftime('%Y-%m-%d-%H.%M.%S')}.xlsx"
+    data = [row.get_row() for row in list_obj]
+    df = pd.DataFrame(data=data)
+    df.to_excel(namefile, index= False)
+    
 if __name__ == '__main__':
     logger.info("Start programm")