Explorar o código

代码静态分析

Huan %!s(int64=5) %!d(string=hai) anos
pai
achega
66d90e9cf1

+ 15 - 30
Hello.py

@@ -1,4 +1,5 @@
 from multiprocessing import Process
 from multiprocessing import Process
+from _tkinter import TclError
 import tkinter
 import tkinter
 from tkinter import ttk
 from tkinter import ttk
 import tkinter.font as tkfont
 import tkinter.font as tkfont
@@ -19,7 +20,7 @@ crawlef_start = None
 
 
 
 
 def progress_bar(func):
 def progress_bar(func):
-    def progress_bar(*agrs, **kwargs):
+    def make_bar(*agrs, **kwargs):
         func(*agrs, **kwargs)
         func(*agrs, **kwargs)
         progress_screen = tkinter.Toplevel()
         progress_screen = tkinter.Toplevel()
         progress_screen.title('系统持续加载中...')
         progress_screen.title('系统持续加载中...')
@@ -35,12 +36,12 @@ def progress_bar(func):
             try:
             try:
                 progress["value"] = i + 1
                 progress["value"] = i + 1
                 progress_screen.update()
                 progress_screen.update()
-            except BaseException:
+            except TclError:
                 pass
                 pass
             SCREEN.update()
             SCREEN.update()
             time.sleep(0.015)
             time.sleep(0.015)
         progress_screen.destroy()
         progress_screen.destroy()
-    return progress_bar
+    return make_bar
 
 
 
 
 def draftboard_main():
 def draftboard_main():
@@ -50,9 +51,7 @@ def draftboard_main():
 
 
 @progress_bar
 @progress_bar
 def draftboard_run():
 def draftboard_run():
-    global SCREEN, draftboard_start
-    draftboard_start = Process(target=draftboard_main)
-    draftboard_start.start()
+    Process(target=draftboard_main).start()
 
 
 
 
 def datascience_main():
 def datascience_main():
@@ -62,35 +61,29 @@ def datascience_main():
 
 
 @progress_bar
 @progress_bar
 def datascience_run():
 def datascience_run():
-    global SCREEN, datascience_start
-    datascience_start = Process(target=datascience_main)
-    datascience_start.start()
+    Process(target=datascience_main).start()
 
 
 
 
 def functionmapping_main():
 def functionmapping_main():
     from funcsystem.map import function_mapping
     from funcsystem.map import function_mapping
+    print('函数测绘加载完毕...')
     function_mapping()
     function_mapping()
 
 
 
 
 @progress_bar
 @progress_bar
 def functionmapping_run():
 def functionmapping_run():
-    global SCREEN, functionmapping_start
-    functionmapping_start = Process(target=functionmapping_main)
-    functionmapping_start.start()
+    Process(target=functionmapping_main).start()
 
 
 
 
 def functionfactory_main():
 def functionfactory_main():
     from funcsystem.factory import function_factory_main
     from funcsystem.factory import function_factory_main
-    print('函数工厂加载完毕')
+    print('函数工厂加载完毕...')
     function_factory_main()
     function_factory_main()
 
 
 
 
 @progress_bar
 @progress_bar
 def functionfactory_run():
 def functionfactory_run():
-    global SCREEN, functionfactory_start
-    functionfactory_start = Process(target=functionfactory_main)
-    print('函数工厂加载完毕')
-    functionfactory_start.start()
+    Process(target=functionfactory_main).start()
 
 
 
 
 def algebraicfactory_main():
 def algebraicfactory_main():
@@ -100,9 +93,7 @@ def algebraicfactory_main():
 
 
 @progress_bar
 @progress_bar
 def algebraicfactory_run():
 def algebraicfactory_run():
-    global SCREEN, algebraicfactory_start
-    algebraicfactory_start = Process(target=algebraicfactory_main)
-    algebraicfactory_start.start()
+    Process(target=algebraicfactory_main).start()
 
 
 
 
 def machinelearner_main():
 def machinelearner_main():
@@ -112,9 +103,7 @@ def machinelearner_main():
 
 
 @progress_bar
 @progress_bar
 def machinelearner_run():
 def machinelearner_run():
-    global SCREEN, machinelearner_start
-    machinelearner_start = Process(target=machinelearner_main)
-    machinelearner_start.start()
+    Process(target=machinelearner_main).start()
 
 
 
 
 def git_main():
 def git_main():
@@ -124,9 +113,7 @@ def git_main():
 
 
 @progress_bar
 @progress_bar
 def git_run():
 def git_run():
-    global SCREEN, git_start
-    git_start = Process(target=git_main)
-    git_start.start()
+    Process(target=git_main).start()
 
 
 
 
 def crawler_main():
 def crawler_main():
@@ -136,8 +123,7 @@ def crawler_main():
 
 
 @progress_bar
 @progress_bar
 def crawlef_run():
 def crawlef_run():
-    crawlef_start = Process(target=crawler_main)
-    crawlef_start.start()
+    Process(target=crawler_main).start()
 
 
 
 
 def system_main():
 def system_main():
@@ -146,8 +132,7 @@ def system_main():
 
 
 
 
 def system_run():  # 不需要进度条
 def system_run():  # 不需要进度条
-    system_start = Process(target=system_main)
-    system_start.start()
+    Process(target=system_main).start()
 
 
 
 
 def cotan_main():
 def cotan_main():

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 183 - 103
algebraicfactory/gui.py


+ 78 - 53
algebraicfactory/template.py

@@ -1,14 +1,40 @@
 from abc import ABCMeta, abstractmethod
 from abc import ABCMeta, abstractmethod
+import os
 
 
 from sympy import simplify, count_ops, Float, Integer, Rational, sympify, factor, factor_list, expand, collect, Add, \
 from sympy import simplify, count_ops, Float, Integer, Rational, sympify, factor, factor_list, expand, collect, Add, \
     Mul, ratsimp, cancel, apart, together, radsimp, trigsimp, expand_trig, expand_mul, expand_multinomial, powdenest, \
     Mul, ratsimp, cancel, apart, together, radsimp, trigsimp, expand_trig, expand_mul, expand_multinomial, powdenest, \
     powsimp, expand_power_base, expand_power_exp, logcombine, expand_log, ceiling, expand_complex, expand_func, Eq, \
     powsimp, expand_power_base, expand_power_exp, logcombine, expand_log, ceiling, expand_complex, expand_func, Eq, \
     Symbol, solve, true, false, plot
     Symbol, solve, true, false, plot
 from sympy.plotting import plot3d
 from sympy.plotting import plot3d
+from sympy.core.sympify import SympifyError
 
 
 from system import plugin_class_loading, get_path, plugin_func_loading
 from system import plugin_class_loading, get_path, plugin_func_loading
 
 
 
 
+class DictNameError(Exception):
+    pass
+
+
+class SymbolError(Exception):
+    pass
+
+
+class ExpError(Exception):
+    pass
+
+
+class FormatError(Exception):
+    pass
+
+
+class SplitError(Exception):
+    pass
+
+
+class MergeError(Exception):
+    pass
+
+
 class AlgebraInit:
 class AlgebraInit:
     def __init__(self, new=lambda x: x):
     def __init__(self, new=lambda x: x):
         self.symbol_dict = {"self": self}  # 命名空间
         self.symbol_dict = {"self": self}  # 命名空间
@@ -21,10 +47,13 @@ class AlgebraInit:
         self.out_status = new
         self.out_status = new
 
 
     def get_expression(self, name, exp_str=False):
     def get_expression(self, name, exp_str=False):
-        if exp_str:
-            return self.algebra_dict_view[name]
-        else:
-            return self.algebra_dict[name]
+        try:
+            if exp_str:
+                return self.algebra_dict_view[name]
+            else:
+                return self.algebra_dict[name]
+        except KeyError:
+            raise DictNameError
 
 
 
 
 class AlgebraSymbolBase(AlgebraInit, metaclass=ABCMeta):
 class AlgebraSymbolBase(AlgebraInit, metaclass=ABCMeta):
@@ -94,17 +123,20 @@ class AlgebraSymbol(AlgebraSymbolBase):
                 k["integer"] = True
                 k["integer"] = True
             try:  # 避免CIR不是list而是None
             try:  # 避免CIR不是list而是None
                 k[is_complex[0]] = is_complex[1]
                 k[is_complex[0]] = is_complex[1]
-            except BaseException:
+            except IndexError:
                 pass
                 pass
             try:  # 避免NZ不是list而是None
             try:  # 避免NZ不是list而是None
                 k[is_natural[0]] = is_natural[1]
                 k[is_natural[0]] = is_natural[1]
-            except BaseException:
+            except (TypeError, IndexError):
                 pass
                 pass
-        except BaseException:
+        except (TypeError, IndexError):
             pass
             pass
         new_name = self.symbol_dict.copy()
         new_name = self.symbol_dict.copy()
         new_name.update({"k": k})
         new_name.update({"k": k})
-        exec(f"self.symbol_dict['{name}'] = Symbol('{name}', **k)", new_name)  # 创建一个Symbols
+        try:
+            exec(f"self.symbol_dict['{name}'] = Symbol('{name}', **k)", new_name)  # 创建一个Symbols
+        except BaseException:
+            raise SymbolError
         self.symbol_describe[name] = describe
         self.symbol_describe[name] = describe
         return True
         return True
 
 
@@ -185,17 +217,14 @@ class AlgebraFormat(AlgebraExpBase, metaclass=ABCMeta):
             elif name == "Rational":
             elif name == "Rational":
                 self.format_rational(f, result_str)
                 self.format_rational(f, result_str)
             elif len(args) < 1:
             elif len(args) < 1:
-                raise Exception
+                raise FormatError
             else:  # 增添逗号
             else:  # 增添逗号
                 result_str = self.format_func(args, name, result_str)
                 result_str = self.format_func(args, name, result_str)
             return result_str
             return result_str
-        except BaseException:
+        except FormatError:
             a = str(f)
             a = str(f)
-            try:
-                if a[0] == "-":
-                    a = f"({a})"
-            except BaseException:
-                pass
+            if a.startswith('-'):
+                a = f"({a})"
             result_str.append(["A", a])
             result_str.append(["A", a])
             return result_str
             return result_str
 
 
@@ -248,8 +277,8 @@ class AlgebraFormat(AlgebraExpBase, metaclass=ABCMeta):
                 b = self.formula_export(f.func(args[0], -args[1]))
                 b = self.formula_export(f.func(args[0], -args[1]))
                 result_str.append(["D", a, b])
                 result_str.append(["D", a, b])
             else:
             else:
-                raise Exception
-        except BaseException:
+                raise FormatError
+        except FormatError:
             a = self.formula_export(args[0])
             a = self.formula_export(args[0])
             b = self.formula_export(args[1])
             b = self.formula_export(args[1])
             result_str.append(["B", a, b])
             result_str.append(["B", a, b])
@@ -265,7 +294,7 @@ class AlgebraPrint(AlgebraExpBase, metaclass=ABCMeta):
             name = e.func.__name__
             name = e.func.__name__
             args = e.args
             args = e.args
             if args == ():
             if args == ():
-                raise Exception
+                raise FormatError
             if name == "log":
             if name == "log":
                 name = "ln"
                 name = "ln"
             str_print += f"({q}){name}\n"
             str_print += f"({q}){name}\n"
@@ -276,7 +305,7 @@ class AlgebraPrint(AlgebraExpBase, metaclass=ABCMeta):
                     i, level + n, first=False, q=q + 1
                     i, level + n, first=False, q=q + 1
                 )
                 )
             return str_print
             return str_print
-        except BaseException:
+        except FormatError:
             return str_print + f"({q}){str(e)}\n"
             return str_print + f"({q}){str(e)}\n"
 
 
     def print_expression_str(self, e, level=0, first=True):  # 直接打印
     def print_expression_str(self, e, level=0, first=True):  # 直接打印
@@ -292,7 +321,7 @@ class AlgebraSplit(AlgebraExpBase, metaclass=ABCMeta):
             args = exp.args
             args = exp.args
             if name not in name_list or args == ():
             if name not in name_list or args == ():
                 if name_list != ["All"]:
                 if name_list != ["All"]:
-                    raise Exception
+                    raise SplitError
                 else:
                 else:
                     deep = 1
                     deep = 1
             if deep == 1:
             if deep == 1:
@@ -307,7 +336,7 @@ class AlgebraSplit(AlgebraExpBase, metaclass=ABCMeta):
                 return re
                 return re
             else:
             else:
                 return args
                 return args
-        except BaseException:
+        except SplitError:
             return [exp]
             return [exp]
 
 
 
 
@@ -315,7 +344,7 @@ class AlgebraSplit(AlgebraExpBase, metaclass=ABCMeta):
 class AlgebraMerge(AlgebraExpBase, metaclass=ABCMeta):
 class AlgebraMerge(AlgebraExpBase, metaclass=ABCMeta):
     def merge_func_core(self, name_list, func):
     def merge_func_core(self, name_list, func):
         if len(name_list) < 2:
         if len(name_list) < 2:
-            return None
+            raise MergeError('长度小于2')
         st = name_list[0]
         st = name_list[0]
         for n in name_list[1:]:
         for n in name_list[1:]:
             st = func(st, n)
             st = func(st, n)
@@ -328,25 +357,22 @@ class AlgebraBase(AlgebraSymbol, AlgebraFormat, AlgebraPrint, AlgebraSplit, Alge
     def simplify(self, alg, radio=1.7, func=None, rat=True, inv=False):  # 函数简化
     def simplify(self, alg, radio=1.7, func=None, rat=True, inv=False):  # 函数简化
         if func is None:
         if func is None:
             func = count_ops
             func = count_ops
+        self.out_status("正在标准化")
         try:
         try:
-            self.out_status("正在标准化")
             return simplify(alg, ratio=radio, func=func, rational=rat, inverse=inv)
             return simplify(alg, ratio=radio, func=func, rational=rat, inverse=inv)
-        except BaseException:
-            return None
+        except SympifyError:
+            raise ExpError('表达式化简错误')
 
 
     def creat_num(self, num, num_type):
     def creat_num(self, num, num_type):
-        try:
-            if num_type == 0:  # 浮点数
-                return Float(num)
-            elif num_type == 1:  # 整数
-                return Integer(num)
-            elif num_type == 2:  # 有理数
-                n = num.split("/")
-                return Rational(n[0], n[1])
-            else:
-                return sympify(num, locals=self.symbol_dict)
-        except BaseException:
-            return Integer(1)
+        if num_type == 0:  # 浮点数
+            return Float(num)
+        elif num_type == 1:  # 整数
+            return Integer(num)
+        elif num_type == 2:  # 有理数
+            n = num.split("/")
+            return Rational(n[0], n[1])
+        else:
+            return sympify(num, locals=self.symbol_dict)
 
 
 
 
 @plugin_class_loading(get_path(r"template/algebraicfactory"))
 @plugin_class_loading(get_path(r"template/algebraicfactory"))
@@ -356,14 +382,13 @@ class AlgebraVisualization(AlgebraBase):
             name = name.replace(" ", "")
             name = name.replace(" ", "")
             try:
             try:
                 exec(f"{name}=5", {})  # 检查name是否符合标准
                 exec(f"{name}=5", {})  # 检查name是否符合标准
-            except BaseException:
+            except SyntaxError:
                 name = f"F{str(len(self.algebra_dict))}"
                 name = f"F{str(len(self.algebra_dict))}"
             eval(f"{alg}", self.symbol_dict)  # 检查
             eval(f"{alg}", self.symbol_dict)  # 检查
             self.algebra_dict[name] = sympify(alg, locals=self.symbol_dict)
             self.algebra_dict[name] = sympify(alg, locals=self.symbol_dict)
             self.algebra_dict_view[name] = str(alg)
             self.algebra_dict_view[name] = str(alg)
-            return True
-        except BaseException:
-            return False
+        except BaseException as e:
+            raise ExpError(str(e))
 
 
     def del_expression(self, name):
     def del_expression(self, name):
         del self.algebra_dict[name]
         del self.algebra_dict[name]
@@ -391,14 +416,14 @@ class AlgebraPolynomialSplit(AlgebraBase):
                 try:
                 try:
                     if return_num:
                     if return_num:
                         if return_one:
                         if return_one:
-                            raise Exception
+                            raise SplitError
                         else:
                         else:
                             if i == 1:
                             if i == 1:
                                 continue
                                 continue
                     else:
                     else:
                         Float(i)
                         Float(i)
                         continue  # 排除数字
                         continue  # 排除数字
-                except BaseException:
+                except SplitError:
                     pass
                     pass
                 useful_exp.append(i)
                 useful_exp.append(i)
         return useful_exp, factor_exp
         return useful_exp, factor_exp
@@ -423,16 +448,16 @@ class AlgebraPolynomialSplit(AlgebraBase):
         if func_name == [""]:
         if func_name == [""]:
             try:
             try:
                 return alg.args, alg
                 return alg.args, alg
-            except BaseException:
+            except AttributeError:
                 return None, alg
                 return None, alg
         get = self.split_func_core(alg, deep, func_name)
         get = self.split_func_core(alg, deep, func_name)
         re = []
         re = []
         if not return_all:
         if not return_all:
             for i in get:
             for i in get:
                 try:
                 try:
-                    if i.args != ():
+                    if not i.args:
                         re.append(i)
                         re.append(i)
-                except BaseException:
+                except AttributeError:
                     pass
                     pass
             return re, alg
             return re, alg
         return get, alg
         return get, alg
@@ -445,7 +470,7 @@ class AlgebraPolynomialMerge(AlgebraBase):
         for n in name_list:
         for n in name_list:
             try:
             try:
                 exp.append(self.get_expression(n))
                 exp.append(self.get_expression(n))
-            except BaseException:
+            except DictNameError:
                 pass
                 pass
         return self.merge_func_core(exp, Add)
         return self.merge_func_core(exp, Add)
 
 
@@ -454,7 +479,7 @@ class AlgebraPolynomialMerge(AlgebraBase):
         for n in name_list:
         for n in name_list:
             try:
             try:
                 exp.append(self.get_expression(n))
                 exp.append(self.get_expression(n))
-            except BaseException:
+            except DictNameError:
                 pass
                 pass
         return self.merge_func_core(exp, Mul)
         return self.merge_func_core(exp, Mul)
 
 
@@ -464,7 +489,7 @@ class AlgebraPolynomialMerge(AlgebraBase):
         for n in name_list:
         for n in name_list:
             try:
             try:
                 name.append(self.get_expression(n))
                 name.append(self.get_expression(n))
-            except BaseException:
+            except DictNameError:
                 pass
                 pass
         return self.merge_func_core(name, func)
         return self.merge_func_core(name, func)
 
 
@@ -701,7 +726,7 @@ class Simultaneous(AlgebraBase):
                 v_alg = self.get_expression(simultaneous_dict[i])  # 获得代数式
                 v_alg = self.get_expression(simultaneous_dict[i])  # 获得代数式
                 get = self.symbol_dict[i]  # 处理符号
                 get = self.symbol_dict[i]  # 处理符号
                 sympy_dict[get] = v_alg
                 sympy_dict[get] = v_alg
-            except BaseException:
+            except (DictNameError, KeyError):
                 pass
                 pass
         return alg.subs(sympy_dict)
         return alg.subs(sympy_dict)
 
 
@@ -713,7 +738,7 @@ class Simultaneous(AlgebraBase):
                 v_alg = self.get_expression(i)  # 获得代数式
                 v_alg = self.get_expression(i)  # 获得代数式
                 get = self.symbol_dict[simultaneous_dict[i]]  # 处理符号
                 get = self.symbol_dict[simultaneous_dict[i]]  # 处理符号
                 sympy_dict[v_alg] = get
                 sympy_dict[v_alg] = get
-            except BaseException:
+            except (DictNameError, KeyError):
                 pass
                 pass
         return alg.subs(sympy_dict)
         return alg.subs(sympy_dict)
 
 
@@ -724,7 +749,7 @@ class Simultaneous(AlgebraBase):
             try:
             try:
                 get = self.symbol_dict[i]  # 处理符号
                 get = self.symbol_dict[i]  # 处理符号
                 sympy_dict[get] = simultaneous_dict[i]
                 sympy_dict[get] = simultaneous_dict[i]
-            except BaseException:
+            except (DictNameError, KeyError):
                 pass
                 pass
         return alg.subs(sympy_dict)
         return alg.subs(sympy_dict)
 
 
@@ -856,5 +881,5 @@ def interpreter(word: str):
     try:
     try:
         results = book[word]
         results = book[word]
         return f"{results}({word})"
         return f"{results}({word})"
-    except BaseException:
+    except KeyError:
         return word
         return word

+ 3 - 3
crawler/controller.py

@@ -40,7 +40,7 @@ class PageParser(PageParserAutomation, PageParserBrowser, PageParserData, PagePa
             elif status is None:
             elif status is None:
                 success_code = "No status"
                 success_code = "No status"
             else:
             else:
-                success_code = "Wrong to run"
+                success_code = f"Wrong to run: {e} "
             self.log.write(
             self.log.write(
                 f"last:[{success_code}];now:[{func_name}];url:{self.url_text} [END]"
                 f"last:[{success_code}];now:[{func_name}];url:{self.url_text} [END]"
             )
             )
@@ -48,7 +48,7 @@ class PageParser(PageParserAutomation, PageParserBrowser, PageParserData, PagePa
             for i in self.element_dict:
             for i in self.element_dict:
                 try:
                 try:
                     value_box.append(f"{i}[{len(i)}] = {self.element_dict[i]}")
                     value_box.append(f"{i}[{len(i)}] = {self.element_dict[i]}")
-                except BaseException:
+                except TypeError:
                     value_box.append(f"{i} = {self.element_dict[i]}")
                     value_box.append(f"{i} = {self.element_dict[i]}")
             update_func(func_name, success_code, value_box)  # 信息更新系统
             update_func(func_name, success_code, value_box)  # 信息更新系统
 
 
@@ -56,5 +56,5 @@ class PageParser(PageParserAutomation, PageParserBrowser, PageParserData, PagePa
         for func_num in range(len(func_list)):
         for func_num in range(len(func_list)):
             func_name = func_list[func_num]
             func_name = func_list[func_num]
             update_log(func_name)
             update_log(func_name)
-            status = self.func_dict[func_name](num=f"{func_num}", name="var")
+            status, e = self.func_dict[func_name](num=f"{func_num}", name="var")
         update_log("运行完成")
         update_log("运行完成")

+ 77 - 21
crawler/gui.py

@@ -6,6 +6,7 @@ import threading
 import crawler.controller
 import crawler.controller
 import crawler.template
 import crawler.template
 from newtkinter import askdirectory
 from newtkinter import askdirectory
+from system import exception_catch
 
 
 SCREEN = tkinter.Tk()
 SCREEN = tkinter.Tk()
 database_list = []
 database_list = []
@@ -71,7 +72,8 @@ database = None
 
 
 class UIAPI:
 class UIAPI:
     @staticmethod
     @staticmethod
-    def get_db_index_gui(object_index):
+    @exception_catch()
+    def get_db_index_gui():
         try:
         try:
             index = eval(object_index.get(), {})
             index = eval(object_index.get(), {})
         except BaseException:
         except BaseException:
@@ -79,17 +81,19 @@ class UIAPI:
         return index
         return index
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_datadase_name_gui():
     def get_datadase_name_gui():
         global database_box, database_list
         global database_box, database_list
         try:
         try:
             return database_list[database_box.curselection()[0]]
             return database_list[database_box.curselection()[0]]
-        except BaseException:
+        except IndexError:
             try:
             try:
                 return database_list[0]
                 return database_list[0]
-            except BaseException:
+            except IndexError:
                 return None
                 return None
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_database_box_gui():
     def update_database_box_gui():
         global database_box, database_list
         global database_box, database_list
         database_list = database.return_database()
         database_list = database.return_database()
@@ -97,6 +101,7 @@ class UIAPI:
         database_box.insert(tkinter.END, *database_list)
         database_box.insert(tkinter.END, *database_list)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_run_status_gui(now_func, status, value_box):
     def update_run_status_gui(now_func, status, value_box):
         global now_running, status_output, variable_box
         global now_running, status_output, variable_box
         now_running.set(now_func)
         now_running.set(now_func)
@@ -105,10 +110,12 @@ class UIAPI:
         variable_box.insert(0, *value_box)
         variable_box.insert(0, *value_box)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_attributes_box_index_gui():
     def get_attributes_box_index_gui():
         return attributes_box.curselection()[0]
         return attributes_box.curselection()[0]
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_attributes_gui():
     def add_attributes_gui():
         name = attributes_name.get()
         name = attributes_name.get()
         value = attributes_value.get()
         value = attributes_value.get()
@@ -118,6 +125,7 @@ class UIAPI:
         return name, value
         return name, value
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_attributes_box_gui():
     def update_attributes_box_gui():
         global attributes_box, attributes_dict
         global attributes_box, attributes_dict
         show = []
         show = []
@@ -127,20 +135,21 @@ class UIAPI:
         attributes_box.insert(tkinter.END, *show)
         attributes_box.insert(tkinter.END, *show)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def third_func_args_gui():  # 方法args统一转换(第三栏目)
     def third_func_args_gui():  # 方法args统一转换(第三栏目)
         global is_special_keys, chains, drag_element, drag_element_index, run_time, operation_object, object_index
         global is_special_keys, chains, drag_element, drag_element_index, run_time, operation_object, object_index
         global type_value
         global type_value
         try:
         try:
             index = int(object_index.get())
             index = int(object_index.get())
-        except BaseException:
+        except ValueError:
             index = 0
             index = 0
         try:
         try:
             index2 = int(drag_element_index.get())
             index2 = int(drag_element_index.get())
-        except BaseException:
+        except ValueError:
             index2 = 0
             index2 = 0
         try:
         try:
             time = int(run_time.get())
             time = int(run_time.get())
-        except BaseException:
+        except ValueError:
             time = 1
             time = 1
         return dict(
         return dict(
             Chains=chains.get(),
             Chains=chains.get(),
@@ -154,6 +163,7 @@ class UIAPI:
         )
         )
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def second_func_args_gui():  # 方法args统一转换(第二栏目)
     def second_func_args_gui():  # 方法args统一转换(第二栏目)
         global cookies_name_input, new_cookies, element_name, attributes_dict, operation_object, object_index
         global cookies_name_input, new_cookies, element_name, attributes_dict, operation_object, object_index
         global find_text, text_regex, limit, is_recursive, find_path
         global find_text, text_regex, limit, is_recursive, find_path
@@ -179,15 +189,16 @@ class UIAPI:
         )
         )
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def first_func_args_gui():  # 方法args统一转换(不支持Frame)
     def first_func_args_gui():  # 方法args统一转换(不支持Frame)
         global operation_object, object_index, send_text, password, select_object, js_code, wait_time
         global operation_object, object_index, send_text, password, select_object, js_code, wait_time
         try:
         try:
             time = int(wait_time.get())
             time = int(wait_time.get())
-        except BaseException:
+        except ValueError:
             time = 2
             time = 2
         try:
         try:
             index = int(object_index.get())
             index = int(object_index.get())
-        except BaseException:
+        except ValueError:
             index = 0
             index = 0
         return dict(
         return dict(
             element_value=operation_object.get(),
             element_value=operation_object.get(),
@@ -201,28 +212,34 @@ class UIAPI:
         )
         )
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_parser_func_box_index_gui():
     def get_parser_func_box_index_gui():
         return parser_func_box.curselection()[0]
         return parser_func_box.curselection()[0]
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_parser_func_box_gui():
     def update_parser_func_box_gui():
         global parser_func_box, page_parser
         global parser_func_box, page_parser
         parser_func_box.delete(0, tkinter.END)
         parser_func_box.delete(0, tkinter.END)
         parser_func_box.insert(tkinter.END, *page_parser.return_func(False)[::-1])
         parser_func_box.insert(tkinter.END, *page_parser.return_func(False)[::-1])
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_new_cookies_gui():
     def get_new_cookies_gui():
         return eval(new_cookies.get(), {})
         return eval(new_cookies.get(), {})
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_cookies_fix_gui():
     def get_cookies_fix_gui():
         return bool(cookies_fixed.get())
         return bool(cookies_fixed.get())
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_cookies_box_index_gui():
     def get_cookies_box_index_gui():
         return cookies_BOX.curselection()[0]
         return cookies_BOX.curselection()[0]
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_cookies_box_gui(cookies):
     def update_cookies_box_gui(cookies):
         global cookies_BOX, cookies_list
         global cookies_BOX, cookies_list
         if API.get_cookies_fix_gui():
         if API.get_cookies_fix_gui():
@@ -231,20 +248,24 @@ class UIAPI:
             cookies_BOX.insert(0, *cookies)
             cookies_BOX.insert(0, *cookies)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_filter_func_box_index_gui():
     def get_filter_func_box_index_gui():
         return filter_func_box.curselection()[0]
         return filter_func_box.curselection()[0]
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_filter_func_box_gui():
     def update_filter_func_box_gui():
         global url, filter_func_box
         global url, filter_func_box
         filter_func_box.delete(0, tkinter.END)
         filter_func_box.delete(0, tkinter.END)
         filter_func_box.insert(tkinter.END, *url.return_filter_func())
         filter_func_box.insert(tkinter.END, *url.return_filter_func())
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_url_box_index_gui():
     def get_url_box_index_gui():
         return url_box.curselection()[0]
         return url_box.curselection()[0]
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_url_parameter_gui():
     def get_url_parameter_gui():
         try:
         try:
             data = eval(requests_data.get(), {})
             data = eval(requests_data.get(), {})
@@ -252,9 +273,9 @@ class UIAPI:
             data = {}
             data = {}
         try:
         try:
             the_time_out = int(time_out.get())
             the_time_out = int(time_out.get())
-        except BaseException:
+        except ValueError:
             the_time_out = 5
             the_time_out = 5
-        re = dict(
+        return_ = dict(
             func=mode_input.get(),
             func=mode_input.get(),
             UA=user_agent_input.get(),
             UA=user_agent_input.get(),
             cookies=applied_cookies.get(),
             cookies=applied_cookies.get(),
@@ -263,14 +284,16 @@ class UIAPI:
         )
         )
         name = ["no_js", "no_java", "no_plugins", "first_run", "head", "no_img", "new"]
         name = ["no_js", "no_java", "no_plugins", "first_run", "head", "no_img", "new"]
         for i in range(len(name)):
         for i in range(len(name)):
-            re[name[i]] = bool(url_parameter[i].get())
-        return re
+            return_[name[i]] = bool(url_parameter[i].get())
+        return return_
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_new_url_name_gui():
     def get_new_url_name_gui():
         return url_input.get()
         return url_input.get()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_url_from_tag_gui():
     def add_url_from_tag_gui():
         try:
         try:
             index = eval(object_index.get(), {})
             index = eval(object_index.get(), {})
@@ -285,14 +308,16 @@ class UIAPI:
         )
         )
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_url_box_gui():
     def update_url_box_gui():
         global url, url_box
         global url, url_box
         url_box.delete(0, tkinter.END)
         url_box.delete(0, tkinter.END)
         url_box.insert(tkinter.END, *url.return_url())
         url_box.insert(tkinter.END, *url.return_url())
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def to_database_gui():
     def to_database_gui():
-        index = API.get_db_index_gui(object_index)
+        index = API.get_db_index_gui()
         return dict(element_value=operation_object.get(),
         return dict(element_value=operation_object.get(),
                     index=index,
                     index=index,
                     data=data_format.get(),
                     data=data_format.get(),
@@ -301,6 +326,7 @@ class UIAPI:
 
 
 class API(UIAPI):
 class API(UIAPI):
     @staticmethod
     @staticmethod
+    @exception_catch()
     def to_database(is_tag=True):
     def to_database(is_tag=True):
         global object_index, operation_object, data_format, page_parser
         global object_index, operation_object, data_format, page_parser
         if is_tag:
         if is_tag:
@@ -311,50 +337,58 @@ class API(UIAPI):
         API.update_parser_func_box_gui()
         API.update_parser_func_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def close():
     def close():
         name = API.get_datadase_name_gui()
         name = API.get_datadase_name_gui()
         database.close(name)
         database.close(name)
         API.update_database_box_gui()
         API.update_database_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def out():
     def out():
         name = API.get_datadase_name_gui()
         name = API.get_datadase_name_gui()
         database.out(name, save_dir)
         database.out(name, save_dir)
         API.update_database_box_gui()
         API.update_database_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def remove_database():
     def remove_database():
         name = API.get_datadase_name_gui()
         name = API.get_datadase_name_gui()
         database.rm_database(name)
         database.rm_database(name)
         API.update_database_box_gui()
         API.update_database_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_database():
     def add_database():
         name = database_name.get()
         name = database_name.get()
         database.add_database(name)
         database.add_database(name)
         API.update_database_box_gui()
         API.update_database_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def clean_attributes():
     def clean_attributes():
         global attributes_dict
         global attributes_dict
         attributes_dict = {}
         attributes_dict = {}
         API.update_attributes_box_gui()
         API.update_attributes_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def del_attributes():
     def del_attributes():
         del attributes_dict[list(attributes_dict.keys())[API.get_attributes_box_index_gui()]]
         del attributes_dict[list(attributes_dict.keys())[API.get_attributes_box_index_gui()]]
         API.update_attributes_box_gui()
         API.update_attributes_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_attributes():
     def add_attributes():
         try:
         try:
             name, value = API.add_attributes_gui()
             name, value = API.add_attributes_gui()
         except BaseException:
         except BaseException:
-            return False
+            raise
         attributes_dict[name] = value
         attributes_dict[name] = value
         API.update_attributes_box_gui()
         API.update_attributes_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def third_add_action_func(func):
     def third_add_action_func(func):
         args = API.third_func_args_gui()
         args = API.third_func_args_gui()
         func = {
         func = {
@@ -376,6 +410,7 @@ class API(UIAPI):
         API.update_parser_func_box_gui()
         API.update_parser_func_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def second_add_action_func(func):
     def second_add_action_func(func):
         args = API.second_func_args_gui()
         args = API.second_func_args_gui()
         func = {
         func = {
@@ -401,6 +436,7 @@ class API(UIAPI):
         API.update_parser_func_box_gui()
         API.update_parser_func_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def first_add_action_func(func):
     def first_add_action_func(func):
         args = API.first_func_args_gui()
         args = API.first_func_args_gui()
         func = {
         func = {
@@ -433,18 +469,21 @@ class API(UIAPI):
         API.update_parser_func_box_gui()
         API.update_parser_func_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_frame_func_father(is_main=True):
     def add_frame_func_father(is_main=True):
         search = None if is_main else ""
         search = None if is_main else ""
         page_parser.find_switch_to_frame(search, True)
         page_parser.find_switch_to_frame(search, True)
         API.update_parser_func_box_gui()
         API.update_parser_func_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_frame_func_id():
     def add_frame_func_id():
         search = API.get_search_key()
         search = API.get_search_key()
         page_parser.find_switch_to_frame(search, True)
         page_parser.find_switch_to_frame(search, True)
         API.update_parser_func_box_gui()
         API.update_parser_func_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_find_func(func):
     def add_find_func(func):
         not_all = not (bool(search_all.get()))
         not_all = not (bool(search_all.get()))
         search = API.get_search_key()
         search = API.get_search_key()
@@ -465,28 +504,32 @@ class API(UIAPI):
         API.update_parser_func_box_gui()
         API.update_parser_func_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_search_key():
     def get_search_key():
         search = search_key.get()
         search = search_key.get()
         return search
         return search
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def del_parser_func():
     def del_parser_func():
         try:
         try:
             index = API.get_parser_func_box_index_gui()
             index = API.get_parser_func_box_index_gui()
             page_parser.del_func(index, True)
             page_parser.del_func(index, True)
             API.update_parser_func_box_gui()
             API.update_parser_func_box_gui()
         except BaseException:
         except BaseException:
-            pass
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def clean_parser_func():
     def clean_parser_func():
         try:
         try:
             page_parser.tra_func()
             page_parser.tra_func()
             API.update_parser_func_box_gui()
             API.update_parser_func_box_gui()
         except BaseException:
         except BaseException:
-            pass
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_cookies():
     def update_cookies():
         cookies = API.get_new_cookies_gui()
         cookies = API.get_new_cookies_gui()
         if API.get_cookies_fix_gui():
         if API.get_cookies_fix_gui():
@@ -496,9 +539,10 @@ class API(UIAPI):
             loader.monitoring_update_cookies(name, cookies)
             loader.monitoring_update_cookies(name, cookies)
             API.set_cookies_fix()
             API.set_cookies_fix()
         except BaseException:
         except BaseException:
-            pass
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_cookies():
     def add_cookies():
         cookies = API.get_new_cookies_gui()
         cookies = API.get_new_cookies_gui()
         if API.get_cookies_fix_gui():
         if API.get_cookies_fix_gui():
@@ -510,6 +554,7 @@ class API(UIAPI):
             raise
             raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def clean_cookies():
     def clean_cookies():
         if API.get_cookies_fix_gui():
         if API.get_cookies_fix_gui():
             return False
             return False
@@ -517,13 +562,15 @@ class API(UIAPI):
             loader.monitoring_clear_cookier()
             loader.monitoring_clear_cookier()
             API.set_cookies_fix()
             API.set_cookies_fix()
         except BaseException:
         except BaseException:
-            pass
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def set_cookies_fix(fix=0):
     def set_cookies_fix(fix=0):
         cookies_fixed.set(fix)
         cookies_fixed.set(fix)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def del_cookies():
     def del_cookies():
         if API.get_cookies_fix_gui():
         if API.get_cookies_fix_gui():
             return False
             return False
@@ -532,15 +579,17 @@ class API(UIAPI):
             loader.monitoring_del_cookies(name)
             loader.monitoring_del_cookies(name)
             API.set_cookies_fix()
             API.set_cookies_fix()
         except BaseException:
         except BaseException:
-            pass
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def crawler_stop():
     def crawler_stop():
         global start_loader_stop
         global start_loader_stop
         start_loader_stop = False
         start_loader_stop = False
         loader.stop()
         loader.stop()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def crawler_run():
     def crawler_run():
         def start_loader():
         def start_loader():
             global start_loader_stop
             global start_loader_stop
@@ -561,6 +610,7 @@ class API(UIAPI):
         API.update_url_box_gui()
         API.update_url_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def crawler_run_one():
     def crawler_run_one():
         def start_loader():
         def start_loader():
             global loader, page_parser
             global loader, page_parser
@@ -575,28 +625,33 @@ class API(UIAPI):
         new.start()
         new.start()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_filter_func_https():
     def add_filter_func_https():
-        url.add_filter_func(lambda url: re.match(re.compile("^https://"), url), "HTTPS过滤")
+        url.add_filter_func(lambda the_url: re.match(re.compile("^https://"), the_url), "HTTPS过滤")
         API.update_filter_func_box_gui()
         API.update_filter_func_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_filter_func_www():
     def add_filter_func_www():
-        url.add_filter_func(lambda url: re.match(re.compile(r".*www\."), url), "www过滤")
+        url.add_filter_func(lambda the_url: re.match(re.compile(r".*www\."), the_url), "www过滤")
         API.update_filter_func_box_gui()
         API.update_filter_func_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def del_filter_func():
     def del_filter_func():
         index = API.get_filter_func_box_index_gui()
         index = API.get_filter_func_box_index_gui()
         url.del_filter_func(index)
         url.del_filter_func(index)
         API.update_filter_func_box_gui()
         API.update_filter_func_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def del_url():
     def del_url():
         index = API.get_url_box_index_gui()
         index = API.get_url_box_index_gui()
         url.del_url(index)
         url.del_url(index)
         API.update_url_box_gui()
         API.update_url_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_url():
     def add_url():
         args = API.get_url_parameter_gui()
         args = API.get_url_parameter_gui()
         new_url = API.get_new_url_name_gui()
         new_url = API.get_new_url_name_gui()
@@ -606,6 +661,7 @@ class API(UIAPI):
         API.update_url_box_gui()
         API.update_url_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_url_from_tag():
     def add_url_from_tag():
         page_parser.add_url(**API.add_url_from_tag_gui())
         page_parser.add_url(**API.add_url_from_tag_gui())
         API.update_parser_func_box_gui()
         API.update_parser_func_box_gui()

+ 63 - 41
crawler/template.py

@@ -5,11 +5,12 @@ import re as regular
 import threading
 import threading
 import time
 import time
 from abc import ABCMeta, abstractmethod
 from abc import ABCMeta, abstractmethod
+from time import sleep
+
 from selenium import webdriver
 from selenium import webdriver
 from selenium.webdriver import ActionChains
 from selenium.webdriver import ActionChains
 from selenium.webdriver.common.keys import Keys
 from selenium.webdriver.common.keys import Keys
-from time import sleep
-
+from selenium.common.exceptions import InvalidSessionIdException, WebDriverException
 import requests
 import requests
 
 
 from system import plugin_class_loading, get_path
 from system import plugin_class_loading, get_path
@@ -40,6 +41,18 @@ keys_name_dict = {
 }  # 键-值映射
 }  # 键-值映射
 
 
 
 
+class PageParserError(Exception):
+    pass
+
+
+class UrlError(Exception):
+    pass
+
+
+class CookiesError(Exception):
+    pass
+
+
 class Database(metaclass=ABCMeta):
 class Database(metaclass=ABCMeta):
     @abstractmethod
     @abstractmethod
     def __str__(self):
     def __str__(self):
@@ -77,7 +90,7 @@ class CoTanDB(Database):
     def close(self):
     def close(self):
         try:
         try:
             self.file.close()
             self.file.close()
-        except BaseException:
+        except IOError:
             pass
             pass
 
 
     def add_new(self, data):
     def add_new(self, data):
@@ -144,7 +157,7 @@ class DatabaseController(AddDatabase, DatabaseControllerCustom):  # data base控
         try:
         try:
             self.database[name].close()
             self.database[name].close()
             del self.database[name]
             del self.database[name]
-        except BaseException:
+        except IndexError:
             pass
             pass
 
 
     def close_all(self):  # 关闭所有数据表
     def close_all(self):  # 关闭所有数据表
@@ -457,6 +470,14 @@ class PagedownloaderBase(SeleniumBase, RequestsBase, metaclass=ABCMeta):
     def set_page_parser(self, parser):
     def set_page_parser(self, parser):
         self.parser = parser
         self.parser = parser
 
 
+    @abstractmethod
+    def monitoring_add_cookies(self, cookies):
+        pass
+
+    @abstractmethod
+    def monitoring_clear_cookier(self):
+        pass
+
 
 
 @plugin_class_loading(get_path(r'template/crawler'))
 @plugin_class_loading(get_path(r'template/crawler'))
 class PageDownloaderRun(PagedownloaderBase, metaclass=ABCMeta):
 class PageDownloaderRun(PagedownloaderBase, metaclass=ABCMeta):
@@ -468,7 +489,7 @@ class PageDownloaderRun(PagedownloaderBase, metaclass=ABCMeta):
         if self.last_mode is not None:
         if self.last_mode is not None:
             try:
             try:
                 self.browser.quit()
                 self.browser.quit()
-            except BaseException:
+            except InvalidSessionIdException:
                 pass
                 pass
         self.last_mode = None
         self.last_mode = None
 
 
@@ -482,9 +503,10 @@ class PageDownloaderRun(PagedownloaderBase, metaclass=ABCMeta):
                 self.selenium_mode(func_cookie, url)
                 self.selenium_mode(func_cookie, url)
             else:  # requests模式
             else:  # requests模式
                 self.requests_mode(func_cookie, url)
                 self.requests_mode(func_cookie, url)
-        except BaseException:  # 避免出现错误而无法设置last_mode,进而无法关闭driver
-            pass
-        self.last_mode = self.url_text.mode
+        except BaseException:
+            raise CookiesError
+        finally:
+            self.last_mode = self.url_text.mode
         self.parser.browser = self.browser
         self.parser.browser = self.browser
         self.parser.init(url)
         self.parser.init(url)
         return self.browser
         return self.browser
@@ -536,7 +558,7 @@ class PageDownloaderRequests(PageDownloaderRun, metaclass=ABCMeta):
     def requests_cookies(self, func_cookie):
     def requests_cookies(self, func_cookie):
         try:
         try:
             parameters = {"cookies": self.cookie_dict[self.url_text.cookies]}
             parameters = {"cookies": self.cookie_dict[self.url_text.cookies]}
-        except BaseException:
+        except KeyError:
             parameters = {}
             parameters = {}
             func_cookie([])
             func_cookie([])
         else:
         else:
@@ -556,26 +578,26 @@ class PageDownloaderSelenium(PageDownloaderRun, metaclass=ABCMeta):
     def selenium_quit(self):
     def selenium_quit(self):
         try:
         try:
             self.browser.quit()
             self.browser.quit()
-        except BaseException:
+        except InvalidSessionIdException:
             pass
             pass
 
 
     def selenium_cookies(self):
     def selenium_cookies(self):
         try:
         try:
             if not self.url_text.new:
             if not self.url_text.new:
-                raise Exception
+                raise UrlError
             cookies_list = self.cookie_dict_list[self.url_text.cookies]
             cookies_list = self.cookie_dict_list[self.url_text.cookies]
-        except BaseException:
+        except (UrlError, KeyError):
             pass
             pass
         else:
         else:
             self.monitoring_clear_cookier()
             self.monitoring_clear_cookier()
             try:
             try:
                 for i in cookies_list:
                 for i in cookies_list:
                     self.monitoring_add_cookies(i)
                     self.monitoring_add_cookies(i)
-            except BaseException:
+            except WebDriverException:
                 pass
                 pass
 
 
-    def start_selenium(self, quit=True):
-        if quit:
+    def start_selenium(self, quit_=True):
+        if quit_:
             self.selenium_quit()
             self.selenium_quit()
         self.browser = webdriver.Chrome(chrome_options=self.url_text.options)
         self.browser = webdriver.Chrome(chrome_options=self.url_text.options)
 
 
@@ -595,7 +617,7 @@ class PageDownloaderSelenium(PageDownloaderRun, metaclass=ABCMeta):
                     func_cookie(cookies)  # 与GUI通信显示cookie
                     func_cookie(cookies)  # 与GUI通信显示cookie
                     self.cookie_dict[url] = cookies
                     self.cookie_dict[url] = cookies
                     time.sleep(0.5)
                     time.sleep(0.5)
-                except BaseException:
+                except WebDriverException:
                     pass
                     pass
 
 
         self.cookie_Thread = threading.Thread(target=update_cookie)
         self.cookie_Thread = threading.Thread(target=update_cookie)
@@ -608,7 +630,7 @@ class PageDownloaderSelenium(PageDownloaderRun, metaclass=ABCMeta):
             self.start_selenium(False)
             self.start_selenium(False)
         try:
         try:
             self.selenium_run(url)
             self.selenium_run(url)
-        except BaseException:
+        except WebDriverException:
             self.start_selenium()
             self.start_selenium()
             self.selenium_run(url)
             self.selenium_run(url)
         self.selenium_cookies()
         self.selenium_cookies()
@@ -630,12 +652,12 @@ class PageParserBase:
 
 
     @staticmethod
     @staticmethod
     def add_base(func):  # 装饰器
     def add_base(func):  # 装饰器
-        def wrap(num=None, name=None, *args, **kwargs) -> bool:
+        def wrap(num=None, name=None, *args, **kwargs):
             try:
             try:
                 func(num=num, name=name, *args, **kwargs)
                 func(num=num, name=name, *args, **kwargs)
-                return True
-            except BaseException:
-                return False
+                return True, ''
+            except BaseException as e:
+                return False, str(e)
 
 
         return wrap
         return wrap
 
 
@@ -670,18 +692,18 @@ class PageParserFunc(PageParserBase):
 
 
 @plugin_class_loading(get_path(r'template/crawler'))
 @plugin_class_loading(get_path(r'template/crawler'))
 class PageParserFind(PageParserFunc):
 class PageParserFind(PageParserFunc):
-    def find_id(self, id, not_all=False, **kwargs):
+    def find_id(self, id_, not_all=False, **kwargs):
         @self.add_base
         @self.add_base
         def find(num, name, *args, **kwargs):
         def find(num, name, *args, **kwargs):
-            nonlocal self, id
+            nonlocal self, id_
             if not_all:
             if not_all:
                 self.element_dict[f"{name}[{num}]"] = [
                 self.element_dict[f"{name}[{num}]"] = [
-                    self.browser.find_element_by_id(id)
+                    self.browser.find_element_by_id(id_)
                 ]  # 返回必须是list
                 ]  # 返回必须是list
             else:
             else:
-                self.element_dict[f"{name}[{num}]"] = self.browser.find_elements_by_id(id)
+                self.element_dict[f"{name}[{num}]"] = self.browser.find_elements_by_id(id_)
 
 
-        self.add_func(f"find_ID:{id}", find)  # 添加func
+        self.add_func(f"find_ID:{id_}", find)  # 添加func
 
 
     def find_class(self, class_name, not_all=False, **kwargs):
     def find_class(self, class_name, not_all=False, **kwargs):
         @self.add_base
         @self.add_base
@@ -1142,7 +1164,7 @@ class PageParserDataFindall(PageParserFunc):
             tag = str(tag).split(",")
             tag = str(tag).split(",")
         try:
         try:
             limit = int(limit)
             limit = int(limit)
-        except BaseException:
+        except ValueError:
             limit = None
             limit = None
 
 
         @self.add_base
         @self.add_base
@@ -1153,20 +1175,20 @@ class PageParserDataFindall(PageParserFunc):
             for bs in iter_list:
             for bs in iter_list:
                 try:
                 try:
                     re = bs.find_all(tag, attribute, limit=limit, recursive=recursive)
                     re = bs.find_all(tag, attribute, limit=limit, recursive=recursive)
-                except BaseException:
+                except AttributeError:
                     try:
                     try:
                         if str(bs.name) not in tag:
                         if str(bs.name) not in tag:
-                            raise Exception
+                            raise PageParserError
                         for agrs_name in attribute:
                         for agrs_name in attribute:
                             text = attribute[agrs_name]
                             text = attribute[agrs_name]
                             if isinstance(text, str):
                             if isinstance(text, str):
                                 if bs.attrs[agrs_name] != text:
                                 if bs.attrs[agrs_name] != text:
-                                    raise Exception
+                                    raise PageParserError
                             else:  # 正则匹配
                             else:  # 正则匹配
                                 if not regular.match(text, bs.attrs[agrs_name]):
                                 if not regular.match(text, bs.attrs[agrs_name]):
-                                    raise Exception
+                                    raise PageParserError
                         re = [bs]
                         re = [bs]
-                    except BaseException:
+                    except PageParserError:
                         re = []
                         re = []
                 paser_list += re
                 paser_list += re
             self.element_dict[f"{name}[{num}]"] = paser_list
             self.element_dict[f"{name}[{num}]"] = paser_list
@@ -1184,7 +1206,7 @@ class PageParserDataFindall(PageParserFunc):
     ):  # 根据text定位
     ):  # 根据text定位
         try:
         try:
             limit = int(limit)
             limit = int(limit)
-        except BaseException:
+        except ValueError:
             limit = None
             limit = None
 
 
         @self.add_base
         @self.add_base
@@ -1195,16 +1217,16 @@ class PageParserDataFindall(PageParserFunc):
             for bs in iter_list:
             for bs in iter_list:
                 try:
                 try:
                     re = bs.find_all(text=text, limit=limit, recursive=recursive)
                     re = bs.find_all(text=text, limit=limit, recursive=recursive)
-                except BaseException:
+                except AttributeError:
                     try:
                     try:
                         if isinstance(text, str):
                         if isinstance(text, str):
                             if str(bs.string) != text:
                             if str(bs.string) != text:
-                                raise Exception
+                                raise PageParserError
                         else:
                         else:
                             if not regular.match(text, str(bs.string)):
                             if not regular.match(text, str(bs.string)):
-                                raise Exception
+                                raise PageParserError
                         re = [bs]
                         re = [bs]
-                    except BaseException:
+                    except PageParserError:
                         re = []
                         re = []
                 paser_list += re
                 paser_list += re
             self.element_dict[f"{name}[{num}]"] = paser_list
             self.element_dict[f"{name}[{num}]"] = paser_list
@@ -1269,7 +1291,7 @@ class PageParserDataSource(PageParserFunc):
                     self.browser.page_source,
                     self.browser.page_source,
                     self.url_text,
                     self.url_text,
                 ]
                 ]
-            except BaseException:
+            except AttributeError:
                 self.element_dict[f"{name}[{num}]"] = [
                 self.element_dict[f"{name}[{num}]"] = [
                     self.browser.text,
                     self.browser.text,
                     self.url_text,
                     self.url_text,
@@ -1327,7 +1349,7 @@ class PageParserDataSource(PageParserFunc):
                     else:
                     else:
                         new_url = bs.attrs.get(url_name, "")
                         new_url = bs.attrs.get(url_name, "")
                     self.downloader.url.add_url(new_url, **url_args)
                     self.downloader.url.add_url(new_url, **url_args)
-                except BaseException:
+                except AttributeError:
                     pass
                     pass
             update_func()  # 更新tkinter
             update_func()  # 更新tkinter
 
 
@@ -1365,9 +1387,9 @@ class PageParserTool(PageParserFunc):
                 try:
                 try:
                     re = eval(str(path), {"self": bs})
                     re = eval(str(path), {"self": bs})
                     if re is None:
                     if re is None:
-                        raise Exception
+                        raise PageParserError
                     paser_list.append(re)
                     paser_list.append(re)
-                except BaseException:
+                finally:
                     pass
                     pass
             self.element_dict[f"{name}[{num}]"] = paser_list
             self.element_dict[f"{name}[{num}]"] = paser_list
 
 

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 194 - 86
datascience/gui.py


A diferenza do arquivo foi suprimida porque é demasiado grande
+ 217 - 270
datascience/template.py


+ 2 - 2
draftboard/board.py

@@ -70,7 +70,7 @@ def func_draw(func_list, pixel_accuracy=1000):
                 x /= pixel_accuracy
                 x /= pixel_accuracy
                 try:
                 try:
                     y = func(x)
                     y = func(x)
-                except BaseException:
+                except ValueError:
                     last_x = None
                     last_x = None
                     last_y = None
                     last_y = None
                     continue
                     continue
@@ -322,7 +322,7 @@ def draw_main():
                         try:
                         try:
                             bg_im = pygame.image.load(tool_set[9]).convert()  # 加载位图
                             bg_im = pygame.image.load(tool_set[9]).convert()  # 加载位图
                             SCREEN.blit(bg_im, (0, 0))  # 绘制位图
                             SCREEN.blit(bg_im, (0, 0))  # 绘制位图
-                        except BaseException:
+                        finally:
                             pass
                             pass
                     # 恢复参数
                     # 恢复参数
                     previous_x = None
                     previous_x = None

+ 4 - 4
draftboard/customfunctions.py

@@ -5,7 +5,7 @@ import tkinter.messagebox
 
 
 SCREEN = None  # 设置屏幕
 SCREEN = None  # 设置屏幕
 func_input = None
 func_input = None
-help = None
+help_ = None
 button = None
 button = None
 logger = None
 logger = None
 bg_color = "#FFFAFA"  # 主颜色
 bg_color = "#FFFAFA"  # 主颜色
@@ -90,7 +90,7 @@ class UIAPI:
 
 
 
 
 def make_func():
 def make_func():
-    global SCREEN, func_input, help, button, logger
+    global SCREEN, func_input, help_, button, logger
     SCREEN = tkinter.Toplevel(bg=bg_color)
     SCREEN = tkinter.Toplevel(bg=bg_color)
     SCREEN.title("")
     SCREEN.title("")
     SCREEN.resizable(width=False, height=False)
     SCREEN.resizable(width=False, height=False)
@@ -104,7 +104,7 @@ def make_func():
         bg=bg_color,
         bg=bg_color,
         fg=word_color,
         fg=word_color,
     )
     )
-    help = tkinter.Button(
+    help_ = tkinter.Button(
         SCREEN,
         SCREEN,
         text="帮助",
         text="帮助",
         command=UIAPI.get_help_gui,
         command=UIAPI.get_help_gui,
@@ -116,6 +116,6 @@ def make_func():
     func_input = tkinter.Entry(SCREEN)
     func_input = tkinter.Entry(SCREEN)
     func_input.pack(fill=tkinter.BOTH)
     func_input.pack(fill=tkinter.BOTH)
     button.pack()
     button.pack()
-    help.pack()
+    help_.pack()
     logger = CustomFuncLogger()
     logger = CustomFuncLogger()
     return logger
     return logger

+ 14 - 12
draftboard/toolbox.py

@@ -126,11 +126,12 @@ class API:
         pen = pen_weight_input.get().replace(" ", "")
         pen = pen_weight_input.get().replace(" ", "")
         try:
         try:
             pen = int(pen)
             pen = int(pen)
-            if UIAPI.askok_gui(f"是否设定大小为{pen}(系统默认大小为:2)"):
-                pen_weight = pen
-        except BaseException:
+        except ValueError:
             if UIAPI.askok_gui("设置失败,是否要切换到中笔吗"):
             if UIAPI.askok_gui("设置失败,是否要切换到中笔吗"):
                 pen_weight = 2
                 pen_weight = 2
+        else:
+            if UIAPI.askok_gui(f"是否设定大小为{pen}(系统默认大小为:2)"):
+                pen_weight = pen
 
 
     @staticmethod
     @staticmethod
     def switch_stroke():
     def switch_stroke():
@@ -180,22 +181,23 @@ class API:
         span_input_str = span_input.get().replace(" ", "")
         span_input_str = span_input.get().replace(" ", "")
         try:
         try:
             span_input_str = int(span_input_str)
             span_input_str = int(span_input_str)
+        except ValueError:
+            span = None
             if tkinter.messagebox.askokcancel(
             if tkinter.messagebox.askokcancel(
-                "提示", f"是否设定跨度为{span_input_str}(跨度代表坐标系一个单位大小的实际像素,系统默认大跨度为:120)"
+                "提示", "是否绘制大跨度的坐标系,确定后返回草图界面任一点三点开始绘制(点击取消可撤销未执行的清空)"
             ):
             ):
-                span = span_input_str
-                coordinate_system_drawing_method = 1
+                coordinate_system_drawing_method = 3
             else:
             else:
                 coordinate_system_drawing_method = None
                 coordinate_system_drawing_method = None
-                span = None
-        except BaseException:
-            span = None
+        else:
             if tkinter.messagebox.askokcancel(
             if tkinter.messagebox.askokcancel(
-                "提示", "是否绘制大跨度的坐标系,确定后返回草图界面任一点三点开始绘制(点击取消可撤销未执行的清空)"
+                "提示", f"是否设定跨度为{span_input_str}(跨度代表坐标系一个单位大小的实际像素,系统默认大跨度为:120)"
             ):
             ):
-                coordinate_system_drawing_method = 3
+                span = span_input_str
+                coordinate_system_drawing_method = 1
             else:
             else:
                 coordinate_system_drawing_method = None
                 coordinate_system_drawing_method = None
+                span = None
 
 
     @staticmethod
     @staticmethod
     def empty():
     def empty():
@@ -217,7 +219,7 @@ class API:
 
 
 
 
 def tool_box():
 def tool_box():
-    global SCREEN, span_input  # 初始化屏幕
+    global SCREEN, span_input, pen_weight_input  # 初始化屏幕
     SCREEN = tkinter.Tk()  # 设置屏幕
     SCREEN = tkinter.Tk()  # 设置屏幕
     SCREEN["bg"] = bg_color
     SCREEN["bg"] = bg_color
     SCREEN.title("Tool")
     SCREEN.title("Tool")

+ 4 - 12
funcsystem/controller.py

@@ -6,12 +6,8 @@ class SheetFunc(SheetMemory, SheetComputing, SheetDataPacket, SheetProperty, She
     def save_csv(self, file_dir):
     def save_csv(self, file_dir):
         if not self.have_data_packet:
         if not self.have_data_packet:
             self.data_packet()  # 检查Cul的计算
             self.data_packet()  # 检查Cul的计算
-        try:
-            self.dataframe.to_csv(file_dir)
-        except BaseException:
-            return False
-        else:
-            return True
+        self.dataframe.to_csv(file_dir)
+        return True
 
 
     def return_list(self):
     def return_list(self):
         # 最值和极值点设计
         # 最值和极值点设计
@@ -41,12 +37,8 @@ class ExpFunc(ExpMemory, ExpComputing, ExpCheck, ExpDataPacket, ExpProperty, Exp
     def save_csv(self, file_dir):
     def save_csv(self, file_dir):
         if not self.have_data_packet:
         if not self.have_data_packet:
             self.data_packet()  # 检查Cul的计算
             self.data_packet()  # 检查Cul的计算
-        try:
-            self.dataframe.to_csv(file_dir)
-        except BaseException:
-            return False
-        else:
-            return True
+        self.dataframe.to_csv(file_dir)
+        return True
 
 
     def return_list(self):  # 导出列表
     def return_list(self):  # 导出列表
         if not self.have_data_packet:
         if not self.have_data_packet:

+ 90 - 42
funcsystem/factory.py

@@ -11,6 +11,7 @@ from matplotlib.animation import FuncAnimation
 
 
 from funcsystem.controller import ExpFunc as ExpFunc
 from funcsystem.controller import ExpFunc as ExpFunc
 from newtkinter import asksaveasfilename
 from newtkinter import asksaveasfilename
+from system import exception_catch
 
 
 func = None
 func = None
 fig = None
 fig = None
@@ -50,6 +51,7 @@ column = 1
 
 
 class UIAPI:
 class UIAPI:
     @staticmethod
     @staticmethod
+    @exception_catch()
     def dichotomy_gui():
     def dichotomy_gui():
         parameters = [100, 0.0001, 0.1, 0.5, False, True, 1000, 0.1, 0.1, False, None]
         parameters = [100, 0.0001, 0.1, 0.5, False, True, 1000, 0.1, 0.1, False, None]
         for i in range(11):
         for i in range(11):
@@ -59,11 +61,12 @@ class UIAPI:
                 else:
                 else:
                     a = float(dicon_parameters[i].get())
                     a = float(dicon_parameters[i].get())
                 parameters[i] = a
                 parameters[i] = a
-            except BaseException:
+            finally:
                 pass
                 pass
         return parameters
         return parameters
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def output_prompt_gui(news):
     def output_prompt_gui(news):
         global prompt_box, prompt_num, SCREEN
         global prompt_box, prompt_num, SCREEN
         prompt_num += 1
         prompt_num += 1
@@ -72,6 +75,7 @@ class UIAPI:
         SCREEN.update()
         SCREEN.update()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def set_func_gui():
     def set_func_gui():
         new_func = func_exp.get().replace(" ", "")
         new_func = func_exp.get().replace(" ", "")
         if new_func == "":
         if new_func == "":
@@ -91,6 +95,7 @@ class UIAPI:
         # 参数的处理
         # 参数的处理
         try:
         try:
             span_str = span_definition.get().replace(" ", "")
             span_str = span_definition.get().replace(" ", "")
+            span = None
             if span_str[0] == "H":
             if span_str[0] == "H":
                 domain = {
                 domain = {
                     "Pi": sympy.pi,
                     "Pi": sympy.pi,
@@ -110,14 +115,12 @@ class UIAPI:
                     "atan": sympy.atan,
                     "atan": sympy.atan,
                 }
                 }
                 span = eval(span_str[1:], domain)
                 span = eval(span_str[1:], domain)
-            else:
-                raise Exception
-        except BaseException:
-            span = None
+        finally:
+            pass
         for i in range(8):
         for i in range(8):
             try:
             try:
                 default_value[i] = float(get[i].get())
                 default_value[i] = float(get[i].get())
-            except BaseException:
+            finally:
                 pass
                 pass
         if span is not None:
         if span is not None:
             default_value[2] = span
             default_value[2] = span
@@ -127,7 +130,7 @@ class UIAPI:
             if style_str[0] not in point_style:
             if style_str[0] not in point_style:
                 style_str[0] = "b"
                 style_str[0] = "b"
             line_style_str = line_style.get(style_str[1], "-")
             line_style_str = line_style.get(style_str[1], "-")
-        except BaseException:
+        except IndexError:
             style_str = ["", ""]
             style_str = ["", ""]
             style_str[0] = random.choice(point_style)
             style_str[0] = random.choice(point_style)
             line_style_str = "-"
             line_style_str = "-"
@@ -139,63 +142,77 @@ class UIAPI:
         return [new_func, name, style]+default_value
         return [new_func, name, style]+default_value
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_y_value_gui():
     def get_y_value_gui():
         return y_value.get().split(",")
         return y_value.get().split(",")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_prediction_box_gui(answer):
     def update_prediction_box_gui(answer):
         prediction_box.delete(0, tkinter.END)
         prediction_box.delete(0, tkinter.END)
         prediction_box.insert(tkinter.END, *answer)
         prediction_box.insert(tkinter.END, *answer)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_projection_value_gui():
     def get_projection_value_gui():
         return projection_value.get
         return projection_value.get
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_proximity_accuracy_gui():
     def get_proximity_accuracy_gui():
         return proximity_accuracy.get()
         return proximity_accuracy.get()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_x_value_derivation_gui():
     def get_x_value_derivation_gui():
         return x_value_derivation.get().split(",")
         return x_value_derivation.get().split(",")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_y_value_symbol_gui():
     def get_y_value_symbol_gui():
         return y_value_symbol.get().split(",")
         return y_value_symbol.get().split(",")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_x_value_gui():
     def get_x_value_gui():
         return x_value.get().split(",")
         return x_value.get().split(",")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_result_box_gui(answer):
     def update_result_box_gui(answer):
         result_box.delete(0, tkinter.END)  # 清空
         result_box.delete(0, tkinter.END)  # 清空
         result_box.insert(tkinter.END, *answer)
         result_box.insert(tkinter.END, *answer)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_y_value_gradient_gui():
     def get_y_value_gradient_gui():
         return y_value_gradient.get()
         return y_value_gradient.get()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def askokcancel_gui(message):
     def askokcancel_gui(message):
         return tkinter.messagebox.askokcancel("提示", message)
         return tkinter.messagebox.askokcancel("提示", message)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_projection_box_gui(result):
     def add_projection_box_gui(result):
         projection_box.insert(tkinter.END, result)
         projection_box.insert(tkinter.END, result)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_sheet_box_gui(sheet):
     def update_sheet_box_gui(sheet):
         sheet_box.delete(0, tkinter.END)
         sheet_box.delete(0, tkinter.END)
         sheet_box.insert(tkinter.END, *sheet)
         sheet_box.insert(tkinter.END, *sheet)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_save_dir_gui():
     def get_save_dir_gui():
         return asksaveasfilename(title="选择导出位置", filetypes=[("CSV", ".csv")])
         return asksaveasfilename(title="选择导出位置", filetypes=[("CSV", ".csv")])
 
 
 
 
 class API(UIAPI):
 class API(UIAPI):
     @staticmethod
     @staticmethod
+    @exception_catch()
     def type_selection(sequence, type_=float, convert=True):  # Float筛选系统
     def type_selection(sequence, type_=float, convert=True):  # Float筛选系统
         x = []
         x = []
         for i in sequence:
         for i in sequence:
@@ -208,6 +225,7 @@ class API(UIAPI):
         return x
         return x
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def save_to_csv():  # 导出CSV
     def save_to_csv():  # 导出CSV
         try:
         try:
             if not func.save_csv(API.get_save_dir_gui()):
             if not func.save_csv(API.get_save_dir_gui()):
@@ -215,16 +233,20 @@ class API(UIAPI):
             API.output_prompt_gui("CSV导出成功")
             API.output_prompt_gui("CSV导出成功")
         except BaseException:
         except BaseException:
             API.output_prompt_gui("CSV导出失败")
             API.output_prompt_gui("CSV导出失败")
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def save_to_sheet():  # 生成表格
     def save_to_sheet():  # 生成表格
         try:
         try:
             API.update_sheet_box_gui(func.return_list())
             API.update_sheet_box_gui(func.return_list())
             API.output_prompt_gui("表格创建成功")
             API.output_prompt_gui("表格创建成功")
         except BaseException:
         except BaseException:
             API.output_prompt_gui("无法创建表格")
             API.output_prompt_gui("无法创建表格")
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def sympy_computing(exp_str) -> tuple:
     def sympy_computing(exp_str) -> tuple:
         try:
         try:
             named_domain = {
             named_domain = {
@@ -246,15 +268,17 @@ class API(UIAPI):
             }
             }
             answer = eval(exp_str, named_domain)
             answer = eval(exp_str, named_domain)
             return answer, True
             return answer, True
-        except BaseException:
+        except (SyntaxError, ZeroDivisionError, NameError, TypeError, ValueError):
             return None, False
             return None, False
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def computing_gui():
     def computing_gui():
-        accuracy, must = API.sympy_computing(prediction_accuracy.get())
-        return accuracy
+        accuracy_, must = API.sympy_computing(prediction_accuracy.get())
+        return accuracy_
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def confirmation_expression(c):
     def confirmation_expression(c):
         get = API.sympy_computing(c)
         get = API.sympy_computing(c)
         if not get[1]:
         if not get[1]:
@@ -262,11 +286,12 @@ class API(UIAPI):
         return get[0]
         return get[0]
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def check_center_of_symmetry():
     def check_center_of_symmetry():
-        accuracy = API.computing_gui()
+        accuracy_ = API.computing_gui()
         try:
         try:
             result = func.check_symmetry_center(
             result = func.check_symmetry_center(
-                API.confirmation_expression(API.get_projection_value_gui()), API.output_prompt_gui, accuracy
+                API.confirmation_expression(API.get_projection_value_gui()), API.output_prompt_gui, accuracy_
             )
             )
             if result[0]:
             if result[0]:
                 API.add_projection_box_gui(result[1])
                 API.add_projection_box_gui(result[1])
@@ -275,13 +300,15 @@ class API(UIAPI):
                 raise Exception
                 raise Exception
         except BaseException:
         except BaseException:
             API.output_prompt_gui("预测失败")
             API.output_prompt_gui("预测失败")
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def check_symmetry_axis():
     def check_symmetry_axis():
-        accuracy = API.computing_gui()
+        accuracy_ = API.computing_gui()
         try:
         try:
             result = func.check_symmetry_axis(
             result = func.check_symmetry_axis(
-                API.confirmation_expression(API.get_projection_value_gui()), API.output_prompt_gui, accuracy
+                API.confirmation_expression(API.get_projection_value_gui()), API.output_prompt_gui, accuracy_
             )
             )
             if result[0]:
             if result[0]:
                 API.add_projection_box_gui(result[1])
                 API.add_projection_box_gui(result[1])
@@ -290,13 +317,15 @@ class API(UIAPI):
                 raise Exception
                 raise Exception
         except BaseException:
         except BaseException:
             API.output_prompt_gui("预测失败")
             API.output_prompt_gui("预测失败")
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def check_periodic():
     def check_periodic():
-        accuracy = API.computing_gui()
+        accuracy_ = API.computing_gui()
         try:
         try:
             result = func.check_periodic(
             result = func.check_periodic(
-                API.confirmation_expression(API.get_projection_value_gui()), API.output_prompt_gui, accuracy
+                API.confirmation_expression(API.get_projection_value_gui()), API.output_prompt_gui, accuracy_
             )
             )
             if result[0]:
             if result[0]:
                 API.add_projection_box_gui(result[1])
                 API.add_projection_box_gui(result[1])
@@ -305,13 +334,15 @@ class API(UIAPI):
                 raise Exception
                 raise Exception
         except BaseException:
         except BaseException:
             API.output_prompt_gui("预测失败")
             API.output_prompt_gui("预测失败")
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def check_monotonic():
     def check_monotonic():
-        accuracy = API.computing_gui()
+        accuracy_ = API.computing_gui()
         try:
         try:
             result = func.check_monotonic(
             result = func.check_monotonic(
-                API.get_projection_value_gui(), API.output_prompt_gui, accuracy
+                API.get_projection_value_gui(), API.output_prompt_gui, accuracy_
             )
             )
             if result[1]:
             if result[1]:
                 API.add_projection_box_gui(result[1])
                 API.add_projection_box_gui(result[1])
@@ -320,8 +351,10 @@ class API(UIAPI):
                 raise Exception
                 raise Exception
         except BaseException:
         except BaseException:
             API.output_prompt_gui("预测失败")
             API.output_prompt_gui("预测失败")
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def clear_memory():
     def clear_memory():
         try:
         try:
             if API.askokcancel_gui(f"确定删除{func}的记忆吗?"):
             if API.askokcancel_gui(f"确定删除{func}的记忆吗?"):
@@ -332,8 +365,10 @@ class API(UIAPI):
                 API.output_prompt_gui("删除取消")
                 API.output_prompt_gui("删除取消")
         except BaseException:
         except BaseException:
             API.output_prompt_gui("删除失败")
             API.output_prompt_gui("删除失败")
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def show_hidden_memory():  # 显示xy
     def show_hidden_memory():  # 显示xy
         try:
         try:
             API.update_result_box_gui([])
             API.update_result_box_gui([])
@@ -341,8 +376,10 @@ class API(UIAPI):
             API.output_prompt_gui("已清空卡槽")
             API.output_prompt_gui("已清空卡槽")
         except BaseException:
         except BaseException:
             API.output_prompt_gui("隐藏(显示)失败")
             API.output_prompt_gui("隐藏(显示)失败")
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def gradient_method_calculation():
     def gradient_method_calculation():
         try:
         try:
             API.output_prompt_gui("计算过程程序可能无响应")
             API.output_prompt_gui("计算过程程序可能无响应")
@@ -358,8 +395,10 @@ class API(UIAPI):
                 API.output_prompt_gui("系统运算无结果")
                 API.output_prompt_gui("系统运算无结果")
         except BaseException:
         except BaseException:
             API.output_prompt_gui("系统运算失败,请注意参数设置")
             API.output_prompt_gui("系统运算失败,请注意参数设置")
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def calculate():
     def calculate():
         try:
         try:
             API.output_prompt_gui("计算过程程序可能无响应")
             API.output_prompt_gui("计算过程程序可能无响应")
@@ -371,9 +410,11 @@ class API(UIAPI):
             API.update_result_box_gui(answer)
             API.update_result_box_gui(answer)
         except BaseException:
         except BaseException:
             API.output_prompt_gui("计算失败")
             API.output_prompt_gui("计算失败")
+            raise
             # raise
             # raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def sympy_calculation_x():
     def sympy_calculation_x():
         try:
         try:
             API.output_prompt_gui("计算过程程序可能无响应")
             API.output_prompt_gui("计算过程程序可能无响应")
@@ -387,15 +428,17 @@ class API(UIAPI):
             API.update_result_box_gui(answer)
             API.update_result_box_gui(answer)
         except BaseException:
         except BaseException:
             API.output_prompt_gui("计算失败")
             API.output_prompt_gui("计算失败")
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def function_differentiation():
     def function_differentiation():
         try:
         try:
             API.output_prompt_gui("计算过程程序可能无响应")
             API.output_prompt_gui("计算过程程序可能无响应")
-            accuracy = API.get_proximity_accuracy_gui()
+            accuracy_ = API.get_proximity_accuracy_gui()
             answer = []
             answer = []
             for i in API.get_x_value_derivation_gui():
             for i in API.get_x_value_derivation_gui():
-                get = func.derivative(i, accuracy)[0]
+                get = func.derivative(i, accuracy_)[0]
                 if get is not None:
                 if get is not None:
                     answer.append(get)
                     answer.append(get)
             if answer:
             if answer:
@@ -407,13 +450,14 @@ class API(UIAPI):
             API.output_prompt_gui("计算失败")
             API.output_prompt_gui("计算失败")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def approximation():  # 逼近法
     def approximation():  # 逼近法
         try:
         try:
             API.output_prompt_gui("计算过程程序可能无响应")
             API.output_prompt_gui("计算过程程序可能无响应")
-            accuracy = API.get_proximity_accuracy_gui()
+            accuracy_ = API.get_proximity_accuracy_gui()
             answer = []
             answer = []
             for i in API.get_x_value_derivation_gui():
             for i in API.get_x_value_derivation_gui():
-                get = func.derivative(i, accuracy, True)[0]
+                get = func.derivative(i, accuracy_, True)[0]
                 if get is not None:
                 if get is not None:
                     answer.append(get)
                     answer.append(get)
             if answer:
             if answer:
@@ -425,6 +469,7 @@ class API(UIAPI):
             API.output_prompt_gui("计算失败")
             API.output_prompt_gui("计算失败")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def dichotomy():  # 二分法
     def dichotomy():  # 二分法
         global dicon_parameters, func, result_box
         global dicon_parameters, func, result_box
         try:
         try:
@@ -432,10 +477,9 @@ class API(UIAPI):
             answer = []
             answer = []
             API.output_prompt_gui("系统运算中")
             API.output_prompt_gui("系统运算中")
             for i in API.get_y_value_gui():
             for i in API.get_y_value_gui():
-                print(i)
                 try:
                 try:
                     answer += func.dichotomy(float(i), *API.dichotomy_gui())[0]
                     answer += func.dichotomy(float(i), *API.dichotomy_gui())[0]
-                except BaseException:
+                finally:
                     pass
                     pass
             if answer:
             if answer:
                 API.output_prompt_gui("系统运算完成")
                 API.output_prompt_gui("系统运算完成")
@@ -443,28 +487,30 @@ class API(UIAPI):
                 API.output_prompt_gui("系统运算无结果")
                 API.output_prompt_gui("系统运算无结果")
             API.update_result_box_gui(answer)
             API.update_result_box_gui(answer)
         except BaseException:
         except BaseException:
-            # raise
             API.output_prompt_gui("系统运算失败")
             API.output_prompt_gui("系统运算失败")
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def property_prediction():
     def property_prediction():
         try:
         try:
-            accuracy = API.computing_gui()
+            accuracy_ = API.computing_gui()
             API.output_prompt_gui("预测过程程序可能无响应")
             API.output_prompt_gui("预测过程程序可能无响应")
-            answer = func.property_prediction(API.output_prompt_gui, True, accuracy)
+            answer = func.property_prediction(API.output_prompt_gui, True, accuracy_)
             API.update_prediction_box_gui(*answer)
             API.update_prediction_box_gui(*answer)
             API.output_prompt_gui("性质预测完成")
             API.output_prompt_gui("性质预测完成")
         except IndexError:
         except IndexError:
             API.output_prompt_gui("性质预测失败")
             API.output_prompt_gui("性质预测失败")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def function_drawing():
     def function_drawing():
         global x_scale, start_x_plot, start_x_polt, span_x_plot, y_scale, start_y_plot, end_y_plot, span_y_plot
         global x_scale, start_x_plot, start_x_polt, span_x_plot, y_scale, start_y_plot, end_y_plot, span_y_plot
         global start_x_limit, end_x_limit, start_y_limit, end_y_limit
         global start_x_limit, end_x_limit, start_y_limit, end_y_limit
         global func, fig, show_point, show_best_value, show_text, plot_type, frame_rate
         global func, fig, show_point, show_best_value, show_text, plot_type, frame_rate
         try:
         try:
             draw_type = plot_type.curselection()[0]
             draw_type = plot_type.curselection()[0]
-        except BaseException:
+        except IndexError:
             draw_type = 0
             draw_type = 0
         # 画板创造
         # 画板创造
         API.output_prompt_gui("生成绘制取...")
         API.output_prompt_gui("生成绘制取...")
@@ -501,7 +547,7 @@ class API(UIAPI):
                         exp_parameter[2] = int(plot_parameter[2])
                         exp_parameter[2] = int(plot_parameter[2])
                         exp_parameter[3] = int(plot_parameter[3])
                         exp_parameter[3] = int(plot_parameter[3])
                         exp_parameter[4] = int(plot_parameter[4])
                         exp_parameter[4] = int(plot_parameter[4])
-                    except BaseException:  # 迭代匹配直到出现错误
+                    finally:
                         pass
                         pass
                     plot_parameter = exp_parameter
                     plot_parameter = exp_parameter
                     x_exp_scale = API.type_selection(
                     x_exp_scale = API.type_selection(
@@ -544,7 +590,7 @@ class API(UIAPI):
                         exp_parameter[2] = int(plot_parameter[2])
                         exp_parameter[2] = int(plot_parameter[2])
                         exp_parameter[3] = int(plot_parameter[3])
                         exp_parameter[3] = int(plot_parameter[3])
                         exp_parameter[4] = int(plot_parameter[4])
                         exp_parameter[4] = int(plot_parameter[4])
-                    except BaseException:  # 迭代匹配直到出现错误
+                    finally:
                         pass
                         pass
                     plot_parameter = exp_parameter
                     plot_parameter = exp_parameter
                     y_exp_scale = API.type_selection(
                     y_exp_scale = API.type_selection(
@@ -570,6 +616,8 @@ class API(UIAPI):
                 y_major_locator = plt.MultipleLocator(2)
                 y_major_locator = plt.MultipleLocator(2)
                 axis.yaxis.set_major_locator(y_major_locator)
                 axis.yaxis.set_major_locator(y_major_locator)
             # 极限
             # 极限
+            _x_limit = [-10, 10]
+            _y_limit = [-10, 10]
             try:
             try:
                 x_limit = API.type_selection(
                 x_limit = API.type_selection(
                     [start_x_limit.get(), end_x_limit.get()], type_=int, convert=False
                     [start_x_limit.get(), end_x_limit.get()], type_=int, convert=False
@@ -579,15 +627,14 @@ class API(UIAPI):
                 )
                 )
                 try:
                 try:
                     _x_limit = [x_limit[0], x_limit[1]]
                     _x_limit = [x_limit[0], x_limit[1]]
-                except BaseException:
+                except IndexError:
                     _x_limit = [-10, 10]
                     _x_limit = [-10, 10]
                 try:
                 try:
                     _y_limit = [y_limit[0], y_limit[1]]
                     _y_limit = [y_limit[0], y_limit[1]]
-                except BaseException:
+                except IndexError:
                     _y_limit = _x_limit
                     _y_limit = _x_limit
-            except BaseException:
-                _x_limit = [-10, 10]
-                _y_limit = [-10, 10]
+            finally:
+                pass
             _x_limit.sort()
             _x_limit.sort()
             _y_limit.sort()
             _y_limit.sort()
             axis.set_xlim(_x_limit)
             axis.set_xlim(_x_limit)
@@ -708,7 +755,7 @@ class API(UIAPI):
 
 
             try:  # 自定义帧率
             try:  # 自定义帧率
                 frame = int(frame_rate.get())
                 frame = int(frame_rate.get())
-            except BaseException:
+            except ValueError:
                 frame = 100
                 frame = 100
             FuncAnimation(
             FuncAnimation(
                 fig,
                 fig,
@@ -744,20 +791,20 @@ class API(UIAPI):
                 return None
                 return None
 
 
             def update(n):
             def update(n):
-                get = func_cul_list[n - 1]
-                ln_list[0].set_text(get[2])
+                get_ = func_cul_list[n - 1]
+                ln_list[0].set_text(get_[2])
                 for i in range(max(m)):
                 for i in range(max(m)):
                     try:
                     try:
-                        x = get[0][i]
-                        y = get[1][i]
+                        x = get_[0][i]
+                        y = get_[1][i]
                         ln_list[i + 1].set_data(x, y)
                         ln_list[i + 1].set_data(x, y)
-                    except BaseException:
+                    except IndexError:
                         ln_list[i + 1].set_data([], [])
                         ln_list[i + 1].set_data([], [])
                 return ln_list
                 return ln_list
 
 
             try:  # 自定义帧率
             try:  # 自定义帧率
                 frame = int(frame_rate.get())
                 frame = int(frame_rate.get())
-            except BaseException:
+            except ValueError:
                 frame = 100
                 frame = 100
             FuncAnimation(
             FuncAnimation(
                 fig, update, frames=plot_x_len, init_func=_init, interval=frame, blit=False
                 fig, update, frames=plot_x_len, init_func=_init, interval=frame, blit=False
@@ -767,6 +814,7 @@ class API(UIAPI):
         return True
         return True
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def set_function():
     def set_function():
         global func
         global func
         default_value = API.set_func_gui()
         default_value = API.set_func_gui()

+ 50 - 11
funcsystem/map.py

@@ -11,6 +11,7 @@ from matplotlib import rcParams
 
 
 from funcsystem.controller import SheetFunc, ExpFunc
 from funcsystem.controller import SheetFunc, ExpFunc
 from newtkinter import askopenfilename, asksaveasfilename
 from newtkinter import askopenfilename, asksaveasfilename
+from system import exception_catch
 
 
 func_logger = []
 func_logger = []
 fig = None
 fig = None
@@ -53,10 +54,12 @@ gui_height = 2
 
 
 class UIAPI:
 class UIAPI:
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_save_dir_gui():
     def get_save_dir_gui():
         return asksaveasfilename(title="选择导出位置", filetypes=[("CSV", ".csv")])
         return asksaveasfilename(title="选择导出位置", filetypes=[("CSV", ".csv")])
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def output_prompt_gui(news):
     def output_prompt_gui(news):
         global prompt_box, prompt_num
         global prompt_box, prompt_num
         prompt_num += 1
         prompt_num += 1
@@ -65,39 +68,47 @@ class UIAPI:
         SCREEN.update()
         SCREEN.update()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_y_value_gradient_gui():
     def get_y_value_gradient_gui():
         parameters = y_value_gradient.get().split("#")  # 拆解输入
         parameters = y_value_gradient.get().split("#")  # 拆解输入
         return parameters
         return parameters
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def dichotomy_gui():
     def dichotomy_gui():
         y = y_value.get().split(",")  # 拆解输入
         y = y_value.get().split(",")  # 拆解输入
         parameters = dicon_parameters.get().split("#")  # 拆解输入
         parameters = dicon_parameters.get().split("#")  # 拆解输入
         return parameters, y
         return parameters, y
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_func_exp_box_index_gui():
     def get_func_exp_box_index_gui():
         return func_exp_box.curselection()[0]
         return func_exp_box.curselection()[0]
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_x_value_gui():
     def get_x_value_gui():
         return x_value.get().split(",")
         return x_value.get().split(",")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_property_box_gui(answer):
     def update_property_box_gui(answer):
         property_box.delete(0, tkinter.END)
         property_box.delete(0, tkinter.END)
         property_box.insert(tkinter.END, *answer)
         property_box.insert(tkinter.END, *answer)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_result_box_gui(answer):
     def update_result_box_gui(answer):
         result_box.delete(0, tkinter.END)
         result_box.delete(0, tkinter.END)
         result_box.insert(tkinter.END, *answer)
         result_box.insert(tkinter.END, *answer)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_func_logger_gui():
     def get_func_logger_gui():
         return func_logger[func_exp_box.curselection()[0]]
         return func_logger[func_exp_box.curselection()[0]]
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_func_gui():
     def add_func_gui():
         get = func_exp.get().replace(" ", "")
         get = func_exp.get().replace(" ", "")
         definition = definition_domain.get().split(",")
         definition = definition_domain.get().split(",")
@@ -109,7 +120,7 @@ class UIAPI:
             if style_str[0] not in point_style:
             if style_str[0] not in point_style:
                 style_str[0] = "b"
                 style_str[0] = "b"
             line_style_str = line_style.get(style_str[1], "-")
             line_style_str = line_style.get(style_str[1], "-")
-        except BaseException:
+        except IndexError:
             style_str = ["", ""]
             style_str = ["", ""]
             style_str[0] = random.choice(point_style)
             style_str[0] = random.choice(point_style)
             line_style_str = "-"
             line_style_str = "-"
@@ -135,16 +146,18 @@ class UIAPI:
                     "atan": math.atan,
                     "atan": math.atan,
                 }
                 }
                 definition[2] = eval(span_str[1:], named_domain)
                 definition[2] = eval(span_str[1:], named_domain)
-        except BaseException:
+        finally:
             pass
             pass
         return get, [name, style] + definition
         return get, [name, style] + definition
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_func_exp_box_gui():
     def update_func_exp_box_gui():
         func_exp_box.delete(0, tkinter.END)
         func_exp_box.delete(0, tkinter.END)
         func_exp_box.insert(tkinter.END, *func_logger)
         func_exp_box.insert(tkinter.END, *func_logger)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def read_csv_gui():
     def read_csv_gui():
         file = askopenfilename(title="载入表格", filetypes=[("CSV", ".csv")])
         file = askopenfilename(title="载入表格", filetypes=[("CSV", ".csv")])
         style_str = func_style.get().split("#")
         style_str = func_style.get().split("#")
@@ -152,7 +165,7 @@ class UIAPI:
             if style_str[0] not in point_style:
             if style_str[0] not in point_style:
                 style_str[0] = "b"
                 style_str[0] = "b"
             line_style_str = line_style.get(style_str[1], "-")
             line_style_str = line_style.get(style_str[1], "-")
-        except BaseException:
+        except IndexError:
             style_str = ["", ""]
             style_str = ["", ""]
             style_str[0] = random.choice(point_style)
             style_str[0] = random.choice(point_style)
             line_style_str = "-"
             line_style_str = "-"
@@ -166,6 +179,7 @@ class UIAPI:
 
 
 class API(UIAPI):
 class API(UIAPI):
     @staticmethod
     @staticmethod
+    @exception_catch()
     def type_selection(iter_object, si=float, no_zero=True):  # Float筛选系统
     def type_selection(iter_object, si=float, no_zero=True):  # Float筛选系统
         x = []
         x = []
         for i in iter_object:
         for i in iter_object:
@@ -178,6 +192,7 @@ class API(UIAPI):
         return x
         return x
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def plot_func():
     def plot_func():
         global func_logger, definition_domain, fig, x_limit, y_limit, y_axis, x_axis
         global func_logger, definition_domain, fig, x_limit, y_limit, y_axis, x_axis
         # 画板创造
         # 画板创造
@@ -203,7 +218,7 @@ class API(UIAPI):
                     exp_parameter[2] = int(plot_parameter[2])
                     exp_parameter[2] = int(plot_parameter[2])
                     exp_parameter[3] = int(plot_parameter[3])
                     exp_parameter[3] = int(plot_parameter[3])
                     exp_parameter[4] = int(plot_parameter[4])
                     exp_parameter[4] = int(plot_parameter[4])
-                except BaseException:  # 迭代匹配直到出现错误
+                finally:
                     pass
                     pass
                 plot_parameter = exp_parameter
                 plot_parameter = exp_parameter
                 x_exp_scale = API.type_selection(
                 x_exp_scale = API.type_selection(
@@ -240,7 +255,7 @@ class API(UIAPI):
                     exp_parameter[2] = int(plot_parameter[2])
                     exp_parameter[2] = int(plot_parameter[2])
                     exp_parameter[3] = int(plot_parameter[3])
                     exp_parameter[3] = int(plot_parameter[3])
                     exp_parameter[4] = int(plot_parameter[4])
                     exp_parameter[4] = int(plot_parameter[4])
-                except BaseException:  # 迭代匹配直到出现错误
+                finally:
                     pass
                     pass
                 plot_parameter = exp_parameter
                 plot_parameter = exp_parameter
                 y_exp_scale = API.type_selection(
                 y_exp_scale = API.type_selection(
@@ -266,20 +281,21 @@ class API(UIAPI):
             y_major_locator = plt.MultipleLocator(2)
             y_major_locator = plt.MultipleLocator(2)
             axis.yaxis.set_major_locator(y_major_locator)
             axis.yaxis.set_major_locator(y_major_locator)
         # 极限
         # 极限
+        _x_limit = [-10, 10]
+        _y_limit = [-10, 10]
         try:
         try:
             _x_limit = API.type_selection(x_limit.get().split(","), si=int, no_zero=False)
             _x_limit = API.type_selection(x_limit.get().split(","), si=int, no_zero=False)
             _y_limit = API.type_selection(y_limit.get().split(","), si=int, no_zero=False)
             _y_limit = API.type_selection(y_limit.get().split(","), si=int, no_zero=False)
             try:
             try:
                 _x_limit = [_x_limit[0], _x_limit[1]]
                 _x_limit = [_x_limit[0], _x_limit[1]]
-            except BaseException:
+            except IndexError:
                 _x_limit = [-10, 10]
                 _x_limit = [-10, 10]
             try:
             try:
                 _y_limit = [_y_limit[0], _y_limit[1]]
                 _y_limit = [_y_limit[0], _y_limit[1]]
-            except BaseException:
+            except IndexError:
                 _y_limit = _x_limit
                 _y_limit = _x_limit
-        except BaseException:
-            _x_limit = [-10, 10]
-            _y_limit = [-10, 10]
+        finally:
+            pass
         _x_limit.sort()
         _x_limit.sort()
         _y_limit.sort()
         _y_limit.sort()
         plt.xlim(_x_limit)
         plt.xlim(_x_limit)
@@ -366,6 +382,7 @@ class API(UIAPI):
         return True
         return True
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_from_csv():  # 添加函数
     def add_from_csv():  # 添加函数
         file, name, style = API.read_csv_gui()
         file, name, style = API.read_csv_gui()
         try:
         try:
@@ -376,8 +393,10 @@ class API(UIAPI):
             API.output_prompt_gui("读取完毕")
             API.output_prompt_gui("读取完毕")
         except BaseException:
         except BaseException:
             API.output_prompt_gui("读取失败")
             API.output_prompt_gui("读取失败")
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_func():  # 添加函数
     def add_func():  # 添加函数
         get, definition = API.add_func_gui()
         get, definition = API.add_func_gui()
         if get and get not in func_str_list:
         if get and get not in func_str_list:
@@ -389,6 +408,7 @@ class API(UIAPI):
             API.output_prompt_gui("函数生成失败")
             API.output_prompt_gui("函数生成失败")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def clean_func_box():  # 添加函数
     def clean_func_box():  # 添加函数
         global func_logger, func_str_list
         global func_logger, func_str_list
         if API.show_askokcancel("是否清空所有函数?)"):
         if API.show_askokcancel("是否清空所有函数?)"):
@@ -398,6 +418,7 @@ class API(UIAPI):
             API.output_prompt_gui("函数清空完毕")
             API.output_prompt_gui("函数清空完毕")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def func_to_sheet_gui():  # 显示xy
     def func_to_sheet_gui():  # 显示xy
         try:
         try:
             func = API.get_func_logger_gui()
             func = API.get_func_logger_gui()
@@ -406,13 +427,15 @@ class API(UIAPI):
             API.output_prompt_gui("表格创建成功")
             API.output_prompt_gui("表格创建成功")
         except BaseException:
         except BaseException:
             API.output_prompt_gui("无法创建表格")
             API.output_prompt_gui("无法创建表格")
-            pass
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def show_askokcancel(message):
     def show_askokcancel(message):
         return tkinter.messagebox.askokcancel("提示", message)
         return tkinter.messagebox.askokcancel("提示", message)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def clean_func_memory():
     def clean_func_memory():
         global x_value, func_exp_box, func_logger
         global x_value, func_exp_box, func_logger
         try:
         try:
@@ -424,8 +447,10 @@ class API(UIAPI):
                 API.output_prompt_gui("删除取消")
                 API.output_prompt_gui("删除取消")
         except BaseException:
         except BaseException:
             API.output_prompt_gui("删除失败")
             API.output_prompt_gui("删除失败")
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def hide_memory():  # 显示xy
     def hide_memory():  # 显示xy
         global func_logger, result_box
         global func_logger, result_box
         try:
         try:
@@ -434,8 +459,10 @@ class API(UIAPI):
             API.output_prompt_gui("已清空卡槽")
             API.output_prompt_gui("已清空卡槽")
         except BaseException:
         except BaseException:
             API.output_prompt_gui("隐藏(显示)失败")
             API.output_prompt_gui("隐藏(显示)失败")
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def show_memory():  # 显示xy
     def show_memory():  # 显示xy
         global func_logger, result_box
         global func_logger, result_box
         try:
         try:
@@ -446,8 +473,10 @@ class API(UIAPI):
             API.output_prompt_gui("输出完成")
             API.output_prompt_gui("输出完成")
         except BaseException:
         except BaseException:
             API.output_prompt_gui("操作失败")
             API.output_prompt_gui("操作失败")
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def property_prediction():
     def property_prediction():
         try:
         try:
             API.output_prompt_gui("预测过程程序可能无响应")
             API.output_prompt_gui("预测过程程序可能无响应")
@@ -458,6 +487,7 @@ class API(UIAPI):
             API.output_prompt_gui("性质预测失败")
             API.output_prompt_gui("性质预测失败")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def calculate():
     def calculate():
         global func_logger, result_box, x_value
         global func_logger, result_box, x_value
         try:
         try:
@@ -469,6 +499,7 @@ class API(UIAPI):
             API.output_prompt_gui("计算失败")
             API.output_prompt_gui("计算失败")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def func_to_csv():  # 导出CSV
     def func_to_csv():  # 导出CSV
         global csv_list
         global csv_list
         try:
         try:
@@ -476,8 +507,10 @@ class API(UIAPI):
             API.output_prompt_gui("CSV导出成功")
             API.output_prompt_gui("CSV导出成功")
         except BaseException:
         except BaseException:
             API.output_prompt_gui("CSV导出失败")
             API.output_prompt_gui("CSV导出失败")
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def del_func():  # 删除函数
     def del_func():  # 删除函数
         global func_logger, func_str_list, func_exp_box
         global func_logger, func_str_list, func_exp_box
         del_index = API.get_func_exp_box_index_gui()
         del_index = API.get_func_exp_box_index_gui()
@@ -487,6 +520,7 @@ class API(UIAPI):
         API.output_prompt_gui("函数删除完毕")
         API.output_prompt_gui("函数删除完毕")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def dichotomy():
     def dichotomy():
         try:
         try:
             API.output_prompt_gui("计算过程程序可能无响应")
             API.output_prompt_gui("计算过程程序可能无响应")
@@ -502,8 +536,10 @@ class API(UIAPI):
             API.update_result_box_gui(answer)
             API.update_result_box_gui(answer)
         except BaseException:
         except BaseException:
             API.output_prompt_gui("系统运算失败")
             API.output_prompt_gui("系统运算失败")
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def gradient_method_calculation():
     def gradient_method_calculation():
         try:
         try:
             API.output_prompt_gui("计算过程程序可能无响应")
             API.output_prompt_gui("计算过程程序可能无响应")
@@ -516,8 +552,10 @@ class API(UIAPI):
             API.update_result_box_gui(answer)
             API.update_result_box_gui(answer)
         except BaseException:
         except BaseException:
             API.output_prompt_gui("系统运算失败,请注意参数设置")
             API.output_prompt_gui("系统运算失败,请注意参数设置")
+            raise
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def func_differentiation():
     def func_differentiation():
         global func_logger, func_exp_box, property_box, func_str_list, func_name, line_style, point_style, func_style
         global func_logger, func_exp_box, property_box, func_str_list, func_name, line_style, point_style, func_style
         try:
         try:
@@ -543,6 +581,7 @@ class API(UIAPI):
                 raise Exception
                 raise Exception
         except BaseException:
         except BaseException:
             API.output_prompt_gui("导函数创建失败")
             API.output_prompt_gui("导函数创建失败")
+            raise
 
 
 
 
 def function_mapping():
 def function_mapping():

+ 68 - 69
funcsystem/template.py

@@ -18,15 +18,12 @@ def to_bool(str_object, hope=False):
         true_list.append("")
         true_list.append("")
     else:
     else:
         false_list.append("")
         false_list.append("")
-    try:
-        str_object = str(str_object)
-        if str_object in false_list:
-            return False
-        elif str_object in true_list:
-            return True
-        else:
-            raise Exception
-    except BaseException:
+    str_object = str(str_object)
+    if str_object in false_list:
+        return False
+    elif str_object in true_list:
+        return True
+    else:
         return bool(str_object)
         return bool(str_object)
 
 
 
 
@@ -185,7 +182,7 @@ class SheetFuncInit(SheetFuncBase):
                 float_y = float(func[1][i])
                 float_y = float(func[1][i])
                 float_x_list.append(float_x)
                 float_x_list.append(float_x)
                 float_y_list.append(float_y)
                 float_y_list.append(float_y)
-            except BaseException:
+            finally:
                 pass
                 pass
         # 筛查重复
         # 筛查重复
         x = []
         x = []
@@ -267,7 +264,7 @@ class SheetDataPacket(SheetFuncInit, metaclass=ABCMeta):
                             elif abs(y - last_y) >= 10 * self.span:
                             elif abs(y - last_y) >= 10 * self.span:
                                 balance = 3
                                 balance = 3
                                 group_score += 5
                                 group_score += 5
-                        except BaseException:
+                        except TypeError:
                             balance = 4
                             balance = 4
                             group_score += 9
                             group_score += 9
                         now_monotonic = 2
                         now_monotonic = 2
@@ -284,7 +281,7 @@ class SheetDataPacket(SheetFuncInit, metaclass=ABCMeta):
                     self.classification_x[-1].append(now_x)
                     self.classification_x[-1].append(now_x)
                     self.classification_y[-1].append(y)
                     self.classification_y[-1].append(y)
                     last_y = y
                     last_y = y
-                except BaseException:
+                finally:
                     pass
                     pass
         except (TypeError, IndexError, ValueError):
         except (TypeError, IndexError, ValueError):
             pass
             pass
@@ -300,7 +297,7 @@ class SheetDataPacket(SheetFuncInit, metaclass=ABCMeta):
                     try:
                     try:
                         new_classification_x[-1] += self.classification_x[i]
                         new_classification_x[-1] += self.classification_x[i]
                         new_classification_y[-1] += self.classification_y[i]
                         new_classification_y[-1] += self.classification_y[i]
-                    except BaseException:  # 按道理不应该出现这个情况
+                    except IndexError:  # 按道理不应该出现这个情况
                         new_classification_x.append(self.classification_x[i])
                         new_classification_x.append(self.classification_x[i])
                         new_classification_y.append(self.classification_y[i])
                         new_classification_y.append(self.classification_y[i])
                 else:
                 else:
@@ -363,7 +360,7 @@ class SheetComputing(SheetFuncInit, metaclass=ABCMeta):
                 ):
                 ):
                     result = [last_y, i]
                     result = [last_y, i]
                     break
                     break
-            except BaseException:
+            finally:
                 pass
                 pass
             last_y = i
             last_y = i
         if result is None:
         if result is None:
@@ -372,7 +369,7 @@ class SheetComputing(SheetFuncInit, metaclass=ABCMeta):
                     if abs(((i + last_y) / 2) - y_in) < 0.1:
                     if abs(((i + last_y) / 2) - y_in) < 0.1:
                         result = [last_y, i]
                         result = [last_y, i]
                         break
                         break
-                except BaseException:
+                finally:
                     pass
                     pass
                 last_y = i
                 last_y = i
         if result is None:
         if result is None:
@@ -401,7 +398,7 @@ class SheetComputing(SheetFuncInit, metaclass=ABCMeta):
                 if i not in self.memore_x:
                 if i not in self.memore_x:
                     self.memore_x.append(i)
                     self.memore_x.append(i)
                     self.memore_y.append(y)
                     self.memore_y.append(y)
-            except BaseException:  # 捕捉运算错误
+            except ValueError:  # 捕捉运算错误
                 continue
                 continue
         self.memory_answer += answer
         self.memory_answer += answer
         self.best_value_core()
         self.best_value_core()
@@ -433,15 +430,15 @@ class SheetProperty(SheetFuncInit, metaclass=ABCMeta):
                     if flat is None:
                     if flat is None:
                         flat = 0
                         flat = 0
                     elif flat == 1:
                     elif flat == 1:
-                        raise Exception
+                        assert True
                 elif symmetry_y == -now_y:
                 elif symmetry_y == -now_y:
                     if flat is None:
                     if flat is None:
                         flat = 1
                         flat = 1
                     elif flat == 0:
                     elif flat == 0:
-                        raise Exception
+                        assert True
                 else:
                 else:
-                    raise Exception
-            except BaseException:
+                    assert True
+            except AssertionError:
                 flat = None
                 flat = None
                 break
                 break
         return flat, [left_x, right_x]
         return flat, [left_x, right_x]
@@ -554,7 +551,7 @@ class SheetProperty(SheetFuncInit, metaclass=ABCMeta):
                 possible_cycle_list.extend(
                 possible_cycle_list.extend(
                     list(set(possible_cycle))
                     list(set(possible_cycle))
                 )  # 这里是extend不是append,相当于 +=
                 )  # 这里是extend不是append,相当于 +=
-            except BaseException:
+            finally:
                 pass
                 pass
 
 
         possible_cycle = []  # a的可能列表
         possible_cycle = []  # a的可能列表
@@ -568,10 +565,11 @@ class SheetProperty(SheetFuncInit, metaclass=ABCMeta):
             elif count == max_count:
             elif count == max_count:
                 possible_cycle.append(i)
                 possible_cycle.append(i)
         try:
         try:
+            assert not possible_cycle
             possible_cycle.sort()
             possible_cycle.sort()
             output_prompt("计算完毕")
             output_prompt("计算完毕")
             return possible_cycle[0], possible_cycle
             return possible_cycle[0], possible_cycle
-        except BaseException:
+        except AssertionError:
             output_prompt("无周期")
             output_prompt("无周期")
             return None, []  # 无结果
             return None, []  # 无结果
 
 
@@ -595,7 +593,7 @@ class SheetProperty(SheetFuncInit, metaclass=ABCMeta):
                     if possible_symmetry_axis:
                     if possible_symmetry_axis:
                         possible_symmetry_axis.append(a)
                         possible_symmetry_axis.append(a)
                 possible_symmetry_axis_list.extend(list(set(possible_symmetry_axis)))
                 possible_symmetry_axis_list.extend(list(set(possible_symmetry_axis)))
-            except BaseException:
+            finally:
                 pass
                 pass
 
 
         possible_symmetry_axis = []  # a的可能列表
         possible_symmetry_axis = []  # a的可能列表
@@ -609,10 +607,11 @@ class SheetProperty(SheetFuncInit, metaclass=ABCMeta):
             elif count == max_count:
             elif count == max_count:
                 possible_symmetry_axis.append(i)
                 possible_symmetry_axis.append(i)
         try:
         try:
+            assert possible_symmetry_axis
             possible_symmetry_axis.sort()  #
             possible_symmetry_axis.sort()  #
             output_prompt("计算完毕")
             output_prompt("计算完毕")
             return possible_symmetry_axis[0], possible_symmetry_axis
             return possible_symmetry_axis[0], possible_symmetry_axis
-        except BaseException:
+        except AssertionError:
             output_prompt("无对称轴")
             output_prompt("无对称轴")
             return None, []  # 无结果
             return None, []  # 无结果
 
 
@@ -631,7 +630,7 @@ class SheetProperty(SheetFuncInit, metaclass=ABCMeta):
                 y = self(start)
                 y = self(start)
                 x = start
                 x = start
                 coordinate_points.append((x, y))
                 coordinate_points.append((x, y))
-            except BaseException:
+            finally:
                 pass
                 pass
 
 
         possible_center_list = []
         possible_center_list = []
@@ -655,12 +654,11 @@ class SheetProperty(SheetFuncInit, metaclass=ABCMeta):
             elif count == max_count:
             elif count == max_count:
                 possible_center.append(i)
                 possible_center.append(i)
         try:
         try:
-            if max_count < 5:
-                raise Exception
+            assert max_count < 5 or not possible_center
             output_prompt("计算完毕")
             output_prompt("计算完毕")
             possible_center.sort()
             possible_center.sort()
             return possible_center[int(len(possible_center) / 2)], possible_center
             return possible_center[int(len(possible_center) / 2)], possible_center
-        except BaseException:
+        except AssertionError:
             output_prompt("无对称中心")
             output_prompt("无对称中心")
             return None, []  # 无结果
             return None, []  # 无结果
 
 
@@ -791,7 +789,7 @@ class ExpFuncInit(ExpFuncBase):
                     self.son_list.append(
                     self.son_list.append(
                         ExpFuncSon(func, style, start, end, span, accuracy, a_start)
                         ExpFuncSon(func, style, start, end, span, accuracy, a_start)
                     )
                     )
-                except BaseException:
+                finally:
                     pass  # 不应该出现
                     pass  # 不应该出现
                 a_start += a_span
                 a_start += a_span
             # 这个是函数名字
             # 这个是函数名字
@@ -854,7 +852,7 @@ class ExpDataPacket(ExpFuncInit, metaclass=ABCMeta):
                             ):
                             ):
                                 balance = 3
                                 balance = 3
                                 group_score += 5
                                 group_score += 5
-                        except BaseException:
+                        except TypeError:
                             balance = 4
                             balance = 4
                             group_score += 9
                             group_score += 9
                         now_monotonic = 2
                         now_monotonic = 2
@@ -894,7 +892,7 @@ class ExpDataPacket(ExpFuncInit, metaclass=ABCMeta):
                     try:
                     try:
                         new_classification_x[-1] += self.classification_x[i]
                         new_classification_x[-1] += self.classification_x[i]
                         new_classification_y[-1] += self.classification_y[i]
                         new_classification_y[-1] += self.classification_y[i]
-                    except BaseException:  # 按道理不应该出现这个情况
+                    except IndexError:  # 按道理不应该出现这个情况
                         new_classification_x.append(self.classification_x[i])
                         new_classification_x.append(self.classification_x[i])
                         new_classification_y.append(self.classification_y[i])
                         new_classification_y.append(self.classification_y[i])
                 else:
                 else:
@@ -1017,7 +1015,7 @@ class ExpComputing(ExpFuncInit, metaclass=ABCMeta):
                 self.memore_y.append(y_value)
                 self.memore_y.append(y_value)
                 answer.append(f"y={y_value} -> x={x}")
                 answer.append(f"y={y_value} -> x={x}")
             return answer, result_list
             return answer, result_list
-        except BaseException:
+        except ValueError:
             return [], []
             return [], []
 
 
     def gradient_calculation(self, y_value, start, end, max_iter=100, accuracy=0.00001):
     def gradient_calculation(self, y_value, start, end, max_iter=100, accuracy=0.00001):
@@ -1025,12 +1023,12 @@ class ExpComputing(ExpFuncInit, metaclass=ABCMeta):
             y_value = float(y_value)
             y_value = float(y_value)
             start = float(start)
             start = float(start)
             end = float(end)
             end = float(end)
-        except BaseException:
+        except ValueError:
             return "", None
             return "", None
         try:
         try:
             max_iter = int(max_iter)
             max_iter = int(max_iter)
             accuracy = float(accuracy)
             accuracy = float(accuracy)
-        except BaseException:
+        except ValueError:
             max_iter = 100
             max_iter = 100
             accuracy = 0.00001
             accuracy = 0.00001
         left = start
         left = start
@@ -1061,7 +1059,7 @@ class ExpComputing(ExpFuncInit, metaclass=ABCMeta):
                     actual_monotony = 1  # 增
                     actual_monotony = 1  # 增
                 else:
                 else:
                     actual_monotony = 0  # 减
                     actual_monotony = 0  # 减
-            except BaseException:
+            except TypeError:
                 contraction_direction = 1
                 contraction_direction = 1
                 actual_monotony = future_monotony
                 actual_monotony = future_monotony
             middle_history = middle_y
             middle_history = middle_y
@@ -1120,7 +1118,7 @@ class ExpComputing(ExpFuncInit, metaclass=ABCMeta):
             zero_minimum_distance = abs(float(zero_minimum_distance))
             zero_minimum_distance = abs(float(zero_minimum_distance))
             expansion_depth = abs(int(expansion_depth))
             expansion_depth = abs(int(expansion_depth))
             secondary_verification_effect = abs(float(secondary_verification_effect))
             secondary_verification_effect = abs(float(secondary_verification_effect))
-        except BaseException:
+        except (ValueError, TypeError):
             allow_original_value = False
             allow_original_value = False
             allow_extended_calculations = True
             allow_extended_calculations = True
             secondary_verification = False
             secondary_verification = False
@@ -1138,7 +1136,7 @@ class ExpComputing(ExpFuncInit, metaclass=ABCMeta):
         y = self.y + self.memore_x
         y = self.y + self.memore_x
         try:
         try:
             y_value = float(y_value)
             y_value = float(y_value)
-        except BaseException:
+        except ValueError:
             return [], []
             return [], []
         try:
         try:
             if (
             if (
@@ -1149,7 +1147,7 @@ class ExpComputing(ExpFuncInit, metaclass=ABCMeta):
             if allow_original_value and y_value in y:  # 如果已经计算过
             if allow_original_value and y_value in y:  # 如果已经计算过
                 num = y.index(y_value)
                 num = y.index(y_value)
                 return x[num]
                 return x[num]
-        except BaseException:
+        finally:
             pass
             pass
         iter_interval = [[self.start, self.end]]  # 准备迭代的列表
         iter_interval = [[self.start, self.end]]  # 准备迭代的列表
         middle_list = []
         middle_list = []
@@ -1171,7 +1169,7 @@ class ExpComputing(ExpFuncInit, metaclass=ABCMeta):
                     middle = (left + right) / 2  # 计算c
                     middle = (left + right) / 2  # 计算c
                     try:
                     try:
                         middle_y = self(middle) - y_value  # 计算c
                         middle_y = self(middle) - y_value  # 计算c
-                    except BaseException:
+                    except TypeError:
                         if expansion_depth > 0:  # 尝试向两边扩张,前提是有deep余额(扩张限制)而且新去见大于cx
                         if expansion_depth > 0:  # 尝试向两边扩张,前提是有deep余额(扩张限制)而且新去见大于cx
                             if abs(left - (middle - new_area_offset)) > expansion_limit:
                             if abs(left - (middle - new_area_offset)) > expansion_limit:
                                 # 增加区间(新区间不包括c,增加了一个偏移kx)
                                 # 增加区间(新区间不包括c,增加了一个偏移kx)
@@ -1294,7 +1292,7 @@ class ExpComputing(ExpFuncInit, metaclass=ABCMeta):
                 if i not in self.memore_x:
                 if i not in self.memore_x:
                     self.memore_x.append(i)
                     self.memore_x.append(i)
                     self.memore_y.append(y)
                     self.memore_y.append(y)
-            except BaseException:  # 捕捉运算错误
+            except ValueError:  # 捕捉运算错误
                 continue
                 continue
         self.best_value_core()
         self.best_value_core()
         self.dataframe = pandas.DataFrame(
         self.dataframe = pandas.DataFrame(
@@ -1307,7 +1305,7 @@ class ExpComputing(ExpFuncInit, metaclass=ABCMeta):
         derivatives = self.derivatives
         derivatives = self.derivatives
         try:
         try:
             delta_x = abs(float(delta_x))
             delta_x = abs(float(delta_x))
-        except BaseException:
+        except (TypeError, ValueError):
             delta_x = 0.1
             delta_x = 0.1
         try:
         try:
             x_value = float(x_value)
             x_value = float(x_value)
@@ -1322,7 +1320,7 @@ class ExpComputing(ExpFuncInit, metaclass=ABCMeta):
                 delta_x = y2 - y1
                 delta_x = y2 - y1
                 derivative_num = delta_x / delta_x
                 derivative_num = delta_x / delta_x
                 derivative_method = "逼近法求值"
                 derivative_method = "逼近法求值"
-        except BaseException:
+        except ValueError:
             return None, None
             return None, None
         answer = f"({derivative_method})x:{x_value} -> {derivative_num}"
         answer = f"({derivative_method})x:{x_value} -> {derivative_num}"
         return answer, derivative_num
         return answer, derivative_num
@@ -1366,15 +1364,15 @@ class ExpProperty(ExpFuncInit, metaclass=ABCMeta):
                     if flat is None:
                     if flat is None:
                         flat = 0
                         flat = 0
                     elif flat == 1:
                     elif flat == 1:
-                        raise Exception
+                        assert True
                 elif symmetry_y == -now_y:
                 elif symmetry_y == -now_y:
                     if flat is None:
                     if flat is None:
                         flat = 1
                         flat = 1
                     elif flat == 0:
                     elif flat == 0:
-                        raise Exception
+                        assert True
                 else:
                 else:
-                    raise Exception
-            except BaseException:
+                    assert True
+            except (AssertionError, ValueError, TypeError):
                 flat = None
                 flat = None
                 break
                 break
         return flat, [a, b]
         return flat, [a, b]
@@ -1444,7 +1442,7 @@ class ExpProperty(ExpFuncInit, metaclass=ABCMeta):
     ):
     ):
         try:
         try:
             accuracy = float(accuracy)
             accuracy = float(accuracy)
-        except BaseException:
+        except ValueError:
             accuracy = None
             accuracy = None
         answer = []
         answer = []
         parity = self.parity()
         parity = self.parity()
@@ -1474,17 +1472,17 @@ class ExpProperty(ExpFuncInit, metaclass=ABCMeta):
             try:
             try:
                 for i in periodic[1][1:]:
                 for i in periodic[1][1:]:
                     answer.append(f"可能的最小正周期:{i}")
                     answer.append(f"可能的最小正周期:{i}")
-            except BaseException:
+            finally:
                 pass
                 pass
             try:
             try:
                 for i in symmetry_axis[1][1:]:
                 for i in symmetry_axis[1][1:]:
                     answer.append(f"可能的对称轴:{i}")
                     answer.append(f"可能的对称轴:{i}")
-            except BaseException:
+            finally:
                 pass
                 pass
             try:
             try:
                 for i in symmetry_center[1][1:]:
                 for i in symmetry_center[1][1:]:
                     answer.append(f"可能的对称中心:{i}")
                     answer.append(f"可能的对称中心:{i}")
-            except BaseException:
+            finally:
                 pass
                 pass
 
 
         return answer
         return answer
@@ -1517,7 +1515,7 @@ class ExpProperty(ExpFuncInit, metaclass=ABCMeta):
                     if a:
                     if a:
                         possible_cycle.append(round(a, self.accuracy))
                         possible_cycle.append(round(a, self.accuracy))
                 possible_cycle_list.extend(list(set(possible_cycle)))  # 不是append
                 possible_cycle_list.extend(list(set(possible_cycle)))  # 不是append
-            except BaseException:
+            finally:
                 pass
                 pass
             start += span
             start += span
 
 
@@ -1532,10 +1530,11 @@ class ExpProperty(ExpFuncInit, metaclass=ABCMeta):
             elif count == max_count:
             elif count == max_count:
                 possible_cycle.append(i)
                 possible_cycle.append(i)
         try:
         try:
+            assert not possible_cycle
             possible_cycle.sort()
             possible_cycle.sort()
             output_prompt("计算完毕")
             output_prompt("计算完毕")
             return possible_cycle[0], possible_cycle
             return possible_cycle[0], possible_cycle
-        except BaseException:
+        except AssertionError:
             output_prompt("无周期")
             output_prompt("无周期")
             return None, []  # 无结果
             return None, []  # 无结果
 
 
@@ -1564,7 +1563,7 @@ class ExpProperty(ExpFuncInit, metaclass=ABCMeta):
                     if a:
                     if a:
                         possible_symmetry_axis.append(round(a, self.accuracy))
                         possible_symmetry_axis.append(round(a, self.accuracy))
                 possible_symmetry_axis_list.extend(list(set(possible_symmetry_axis)))
                 possible_symmetry_axis_list.extend(list(set(possible_symmetry_axis)))
-            except BaseException:
+            finally:
                 pass
                 pass
             start += span
             start += span
 
 
@@ -1579,10 +1578,11 @@ class ExpProperty(ExpFuncInit, metaclass=ABCMeta):
             elif n_c == c:
             elif n_c == c:
                 possible_symmetry_axis.append(i)
                 possible_symmetry_axis.append(i)
         try:
         try:
+            assert not possible_symmetry_axis
             possible_symmetry_axis.sort()  #
             possible_symmetry_axis.sort()  #
             output_prompt("计算完毕")
             output_prompt("计算完毕")
             return possible_symmetry_axis[0], possible_symmetry_axis
             return possible_symmetry_axis[0], possible_symmetry_axis
-        except BaseException:
+        except AssertionError:
             output_prompt("无对称轴")
             output_prompt("无对称轴")
             return None, []  # 无结果
             return None, []  # 无结果
 
 
@@ -1604,7 +1604,7 @@ class ExpProperty(ExpFuncInit, metaclass=ABCMeta):
                 y = self(start)
                 y = self(start)
                 x = start
                 x = start
                 coordinate_points.append((x, y))
                 coordinate_points.append((x, y))
-            except BaseException:
+            finally:
                 pass
                 pass
             start += span
             start += span
         possible_center_list = []
         possible_center_list = []
@@ -1628,12 +1628,11 @@ class ExpProperty(ExpFuncInit, metaclass=ABCMeta):
             elif count == max_count:
             elif count == max_count:
                 possible_center.append(i)
                 possible_center.append(i)
         try:
         try:
-            if max_count < 5:
-                raise Exception
+            assert max_count < 5 or not possible_center
             output_prompt("计算完毕")
             output_prompt("计算完毕")
             possible_center.sort()  #
             possible_center.sort()  #
             return possible_center[int(len(possible_center) / 2)], possible_center
             return possible_center[int(len(possible_center) / 2)], possible_center
-        except BaseException:
+        except AssertionError:
             output_prompt("无对称中心")
             output_prompt("无对称中心")
             return None, []  # 无结果
             return None, []  # 无结果
 
 
@@ -1649,7 +1648,7 @@ class ExpCheck(ExpFuncInit, metaclass=ABCMeta):
             start = float(parameters[0])
             start = float(parameters[0])
             end = float(parameters[1])
             end = float(parameters[1])
             flat = int(parameters[2])  # 当前研究反围:0-增区间,1-减区间,2-不增不减
             flat = int(parameters[2])  # 当前研究反围:0-增区间,1-减区间,2-不增不减
-        except BaseException:
+        except (IndexError, ValueError):
             return False, ""
             return False, ""
         if start > end:
         if start > end:
             start, end = end, start
             start, end = end, start
@@ -1662,7 +1661,7 @@ class ExpCheck(ExpFuncInit, metaclass=ABCMeta):
             try:
             try:
                 output_prompt("迭代运算...")
                 output_prompt("迭代运算...")
                 now_y = round(self(start), self.accuracy)
                 now_y = round(self(start), self.accuracy)
-            except BaseException:
+            except (TypeError, ValueError):
                 start += span
                 start += span
                 continue
                 continue
             if last_y is None:
             if last_y is None:
@@ -1692,7 +1691,7 @@ class ExpCheck(ExpFuncInit, metaclass=ABCMeta):
         result = True
         result = True
         try:
         try:
             parameters = float(parameters)
             parameters = float(parameters)
-        except BaseException:
+        except ValueError:
             return False, ""
             return False, ""
         start = self.start
         start = self.start
         end = self.end
         end = self.end
@@ -1707,7 +1706,7 @@ class ExpCheck(ExpFuncInit, metaclass=ABCMeta):
                 last_y = round(self(start + parameters), self.accuracy)
                 last_y = round(self(start + parameters), self.accuracy)
                 if now_y != last_y:
                 if now_y != last_y:
                     result = False
                     result = False
-            except BaseException:
+            finally:
                 pass
                 pass
             start += span
             start += span
         result_key = {True: "是", False: "不是"}
         result_key = {True: "是", False: "不是"}
@@ -1719,7 +1718,7 @@ class ExpCheck(ExpFuncInit, metaclass=ABCMeta):
         result = True
         result = True
         try:
         try:
             parameters = 2 * float(parameters)
             parameters = 2 * float(parameters)
-        except BaseException:
+        except (ValueError, TypeError):
             return False, ""
             return False, ""
         start = self.start
         start = self.start
         end = self.end
         end = self.end
@@ -1734,7 +1733,7 @@ class ExpCheck(ExpFuncInit, metaclass=ABCMeta):
                 last_y = round(self(parameters - start), self.accuracy)
                 last_y = round(self(parameters - start), self.accuracy)
                 if now_y != last_y:
                 if now_y != last_y:
                     result = False
                     result = False
-            except BaseException:
+            finally:
                 pass
                 pass
             start += span
             start += span
         result_key = {True: "是", False: "不是"}
         result_key = {True: "是", False: "不是"}
@@ -1748,7 +1747,7 @@ class ExpCheck(ExpFuncInit, metaclass=ABCMeta):
             parameters = []
             parameters = []
             for i in parameters_input.split(","):
             for i in parameters_input.split(","):
                 parameters.append(float(i))
                 parameters.append(float(i))
-        except BaseException:
+        except ValueError:
             return False, ""
             return False, ""
         start = self.start
         start = self.start
         end = self.end
         end = self.end
@@ -1763,7 +1762,7 @@ class ExpCheck(ExpFuncInit, metaclass=ABCMeta):
                 last_y = round(self(2 * parameters[0] - start), self.accuracy)
                 last_y = round(self(2 * parameters[0] - start), self.accuracy)
                 if round((now_y + last_y) / 2, self.accuracy) != parameters[1]:
                 if round((now_y + last_y) / 2, self.accuracy) != parameters[1]:
                     result = False
                     result = False
-            except BaseException:
+            finally:
                 pass
                 pass
             start += span
             start += span
         result_key = {True: "是", False: "不是"}
         result_key = {True: "是", False: "不是"}
@@ -1896,7 +1895,7 @@ class ExpFuncSon:
                             ):
                             ):
                                 balance = 3
                                 balance = 3
                                 group_score += 5
                                 group_score += 5
-                        except BaseException:
+                        except (ValueError, TypeError):
                             balance = 4
                             balance = 4
                             group_score += 9
                             group_score += 9
                         now_monotonic = 2
                         now_monotonic = 2
@@ -1916,7 +1915,7 @@ class ExpFuncSon:
                     self.classification_x[-1].append(accuracy_x)
                     self.classification_x[-1].append(accuracy_x)
                     self.classification_y[-1].append(now_y)
                     self.classification_y[-1].append(now_y)
                     last_y = now_y
                     last_y = now_y
-                except BaseException:
+                except (ValueError, TypeError):
                     classification_reason.append(0)
                     classification_reason.append(0)
                     self.classification_x.append([])
                     self.classification_x.append([])
                     self.classification_y.append([])
                     self.classification_y.append([])
@@ -1935,7 +1934,7 @@ class ExpFuncSon:
                     try:
                     try:
                         new_classification_x[-1] += self.classification_x[i]
                         new_classification_x[-1] += self.classification_x[i]
                         new_classification_y[-1] += self.classification_y[i]
                         new_classification_y[-1] += self.classification_y[i]
-                    except BaseException:  # 按道理不应该出现这个情况
+                    except IndexError:  # 按道理不应该出现这个情况
                         new_classification_x.append(self.classification_x[i])
                         new_classification_x.append(self.classification_x[i])
                         new_classification_y.append(self.classification_y[i])
                         new_classification_y.append(self.classification_y[i])
                 else:
                 else:

+ 3 - 6
gitrepo/controller.py

@@ -153,13 +153,10 @@ class GitCtrol:
         return self.get_git(name).clone(url)
         return self.get_git(name).clone(url)
 
 
     def after_clone(self, name):
     def after_clone(self, name):
-        try:
-            return self.get_git(name).after_clone()
-        except BaseException:
-            return None
+        return self.get_git(name).after_clone()
 
 
-    def make_dir(self, name, dir):
-        return self.get_git(name).make_dir(dir)
+    def make_dir(self, name, dir_):
+        return self.get_git(name).make_dir(dir_)
 
 
     def rename_branch(self, name, old_name, new_name):
     def rename_branch(self, name, old_name, new_name):
         return self.get_git(name).rename_branch(old_name, new_name)
         return self.get_git(name).rename_branch(old_name, new_name)

+ 118 - 51
gitrepo/gui.py

@@ -10,10 +10,12 @@ from tkinter.scrolledtext import ScrolledText
 
 
 import gitrepo.template
 import gitrepo.template
 from gitrepo import controller
 from gitrepo import controller
+from system import exception_catch
 
 
 
 
 class UIAPI:
 class UIAPI:
     @staticmethod
     @staticmethod
+    @exception_catch()
     def cli_gui(
     def cli_gui(
             func,
             func,
             args,
             args,
@@ -31,14 +33,7 @@ class UIAPI:
         def save_to_txt():
         def save_to_txt():
             nonlocal data
             nonlocal data
             dic = asksaveasfilename(title="选择文件保存位置", filetypes=[("TXT", ".txt")])
             dic = asksaveasfilename(title="选择文件保存位置", filetypes=[("TXT", ".txt")])
-            try:
-                if dic == "":
-                    return False
-                if dic[-4] == ".txt":
-                    pass
-                else:
-                    raise Exception
-            except BaseException:
+            if not dic.endswith(".txt"):
                 dic += ".txt"
                 dic += ".txt"
             with open(dic, "w", encoding="utf-8") as f:
             with open(dic, "w", encoding="utf-8") as f:
                 f.write(data)
                 f.write(data)
@@ -68,7 +63,7 @@ class UIAPI:
         def pipe():
         def pipe():
             pass
             pass
 
 
-        def format():
+        def format_information():
             nonlocal text, out_data, data, format_flat
             nonlocal text, out_data, data, format_flat
             text.clear()
             text.clear()
             if format_flat:
             if format_flat:
@@ -83,7 +78,7 @@ class UIAPI:
 
 
         if show_screen:
         if show_screen:
             text, cli_screen, button_list = API.show_cli_gui(
             text, cli_screen, button_list = API.show_cli_gui(
-                save_to_txt, stop, keep, format, pipe, name=name
+                save_to_txt, stop, keep, format_information, pipe, name=name
             )  # [close,keep]
             )  # [close,keep]
             update_button()
             update_button()
             if tip_text != "":
             if tip_text != "":
@@ -120,13 +115,11 @@ class UIAPI:
                     if show_screen:
                     if show_screen:
                         try:
                         try:
                             cli_screen.update()
                             cli_screen.update()
-                        except BaseException:
+                        finally:
                             pass
                             pass
-                    if time.time() - start >= break_time != 0:
-                        raise Exception
-                    elif break_time == 0 and start == 0:
-                        raise Exception
-                except BaseException:
+                    assert time.time() - start >= break_time != 0
+                    assert break_time == 0 and start == 0
+                except AssertionError:
                     start = 0
                     start = 0
                     break
                     break
 
 
@@ -157,9 +150,9 @@ class UIAPI:
                     break
                     break
                 try:  # 如果界面被关掉了,会报错
                 try:  # 如果界面被关掉了,会报错
                     cli_screen.title(f"{name} : 运行中")
                     cli_screen.title(f"{name} : 运行中")
-                except BaseException:
+                except tkinter.TclError:
                     text, cli_screen, button_list = API.show_cli_gui(
                     text, cli_screen, button_list = API.show_cli_gui(
-                        save_to_txt, stop, keep, format, pipe, name=f"{name} : 运行中"
+                        save_to_txt, stop, keep, format_information, pipe, name=f"{name} : 运行中"
                     )
                     )
                     update_button()
                     update_button()
                     text.insert(tkinter.END, out_data)
                     text.insert(tkinter.END, out_data)
@@ -177,9 +170,9 @@ class UIAPI:
                 # 界面设置
                 # 界面设置
                 try:  # 如果界面被关掉了,会报错
                 try:  # 如果界面被关掉了,会报错
                     cli_screen.title(f"{name} : 运行中")
                     cli_screen.title(f"{name} : 运行中")
-                except BaseException:
+                except tkinter.TclError:
                     text, cli_screen, button_list = API.show_cli_gui(
                     text, cli_screen, button_list = API.show_cli_gui(
-                        save_to_txt, stop, keep, format, pipe, name=f"{name} : 运行中"
+                        save_to_txt, stop, keep, format_information, pipe, name=f"{name} : 运行中"
                     )
                     )
                     update_button()
                     update_button()
                     text.insert(tkinter.END, out_data)
                     text.insert(tkinter.END, out_data)
@@ -188,7 +181,7 @@ class UIAPI:
                     if not is_threaded_refresh:
                     if not is_threaded_refresh:
                         SCREEN.update()
                         SCREEN.update()
                         cli_screen.update()
                         cli_screen.update()
-                except BaseException:
+                except tkinter.TclError:
                     break
                     break
                 # 输出字符
                 # 输出字符
                 try:
                 try:
@@ -212,30 +205,28 @@ class UIAPI:
                         data += f"[END]"
                         data += f"[END]"
                         break
                         break
                     elif command_thread.returncode is not None:
                     elif command_thread.returncode is not None:
-                        raise Exception
-                except BaseException:
-                    try:
-                        if show_screen:
-                            text.insert(tkinter.END, "[ERROR]")
-                            out_data += f"[ERROR]"
-                            data += f"[ERROR]"
-                        raise Exception
-                    except BaseException:
-                        break
+                        assert True
+                except (tkinter.TclError, AssertionError):
+                    if show_screen:
+                        text.insert(tkinter.END, "[ERROR]")
+                        out_data += f"[ERROR]"
+                        data += f"[ERROR]"
+                    break
             try:  # 如果界面被关掉了,会报错
             try:  # 如果界面被关掉了,会报错
                 if show_screen:
                 if show_screen:
                     cli_screen.title(f"{name} : 运行完毕")
                     cli_screen.title(f"{name} : 运行完毕")
-            except BaseException:
+            except tkinter.TclError:
                 pass
                 pass
             command_thread.kill()
             command_thread.kill()
         try:
         try:
             button_list[0].config(state=tkinter.DISABLED)
             button_list[0].config(state=tkinter.DISABLED)
             button_list[1].config(state=tkinter.DISABLED)
             button_list[1].config(state=tkinter.DISABLED)
-        except BaseException:
+        except (AttributeError, NameError):
             pass
             pass
         return data
         return data
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def progress_bar_gui(*args, name="CoTan_Git >>> 运行中...", **kwargs):
     def progress_bar_gui(*args, name="CoTan_Git >>> 运行中...", **kwargs):
         progress_screen = tkinter.Toplevel(bg=bg_color)
         progress_screen = tkinter.Toplevel(bg=bg_color)
         progress_screen.title(name)
         progress_screen.title(name)
@@ -255,12 +246,14 @@ class UIAPI:
         progress_screen.destroy()
         progress_screen.destroy()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_commit_id_gui():
     def get_commit_id_gui():
         global commit
         global commit
         the_commit = commit.get()
         the_commit = commit.get()
         return the_commit
         return the_commit
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def show_cli_gui(
     def show_cli_gui(
             out_func, close_func, keep_func, not_out, pipe_func, name="CoTan_Git >>> 命令行"
             out_func, close_func, keep_func, not_out, pipe_func, name="CoTan_Git >>> 命令行"
     ):
     ):
@@ -344,6 +337,7 @@ class UIAPI:
         return text, cli_screen, [close, keep]
         return text, cli_screen, [close, keep]
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def repo_init_gui():
     def repo_init_gui():
         new_dir = askdirectory(title="选择仓库地址")
         new_dir = askdirectory(title="选择仓库地址")
         if new_dir == "":
         if new_dir == "":
@@ -351,17 +345,19 @@ class UIAPI:
         return new_dir
         return new_dir
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_repo_name_gui():  # 获得名字统一接口
     def get_repo_name_gui():  # 获得名字统一接口
         global git, repo_list, repo_box
         global git, repo_list, repo_box
         try:
         try:
             return repo_list[repo_box.curselection()[0]]
             return repo_list[repo_box.curselection()[0]]
-        except BaseException:
+        except IndexError:
             try:
             try:
                 return repo_list[0]
                 return repo_list[0]
-            except BaseException:
+            except IndexError:
                 return None
                 return None
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_repo_box_gui():
     def update_repo_box_gui():
         global git, repo_list, repo_box
         global git, repo_list, repo_box
         repo_list = list(git.get_git_dict().keys())
         repo_list = list(git.get_git_dict().keys())
@@ -369,12 +365,14 @@ class UIAPI:
         repo_box.insert(tkinter.END, *repo_list)
         repo_box.insert(tkinter.END, *repo_list)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_file_box_gui():
     def update_file_box_gui():
         global file_list, file_box
         global file_list, file_box
         file_box.delete(0, tkinter.END)
         file_box.delete(0, tkinter.END)
         file_box.insert(tkinter.END, *file_list)
         file_box.insert(tkinter.END, *file_list)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_git_file_last_gui():
     def update_git_file_last_gui():
         global last_name
         global last_name
         if last_name is None:
         if last_name is None:
@@ -382,22 +380,25 @@ class UIAPI:
         API.update_git_file_gui(last_name)
         API.update_git_file_gui(last_name)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_git_file_select_gui():
     def update_git_file_select_gui():
         name = API.get_repo_name_gui()
         name = API.get_repo_name_gui()
         API.update_git_file_gui(name)
         API.update_git_file_gui(name)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_git_file_gui(name):
     def update_git_file_gui(name):
         global git, repo_dir, last_name
         global git, repo_dir, last_name
         dir_list = git.get_dir(name)
         dir_list = git.get_dir(name)
         try:  # 窗口可能已经关闭
         try:  # 窗口可能已经关闭
             repo_dir.delete(0, tkinter.END)
             repo_dir.delete(0, tkinter.END)
             repo_dir.insert(tkinter.END, *dir_list)
             repo_dir.insert(tkinter.END, *dir_list)
-        except BaseException:
+        finally:
             pass
             pass
         last_name = name
         last_name = name
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_file_list_gui():
     def add_file_list_gui():
         global file_list, file_box
         global file_list, file_box
         new_file = set(askopenfilenames(title=f"选择文件"))
         new_file = set(askopenfilenames(title=f"选择文件"))
@@ -406,6 +407,7 @@ class UIAPI:
         API.update_file_box_gui()
         API.update_file_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_file_input_dir_gui():
     def add_file_input_dir_gui():
         global file_dir
         global file_dir
         new_dir = file_dir.get()
         new_dir = file_dir.get()
@@ -414,6 +416,7 @@ class UIAPI:
         API.update_file_box_gui()
         API.update_file_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_file_by_git_gui():
     def add_file_by_git_gui():
         global file_dir
         global file_dir
         new_dir = file_dir.get()
         new_dir = file_dir.get()
@@ -425,6 +428,7 @@ class UIAPI:
         API.update_file_box_gui()
         API.update_file_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def diff_gui():
     def diff_gui():
         branch = master.get()
         branch = master.get()
         if branch == "":
         if branch == "":
@@ -432,6 +436,7 @@ class UIAPI:
         return branch
         return branch
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def commit_file_gui():
     def commit_file_gui():
         m = commit_message.get()
         m = commit_message.get()
         if m.replace(" ", "") == "":
         if m.replace(" ", "") == "":
@@ -440,13 +445,15 @@ class UIAPI:
         return m
         return m
 
 
     @staticmethod
     @staticmethod
-    def log_gui(log_type):
-        graph = bool(log_type[0].get())
-        abbrev = bool(log_type[1].get())
-        pretty = bool(log_type[2].get())
+    @exception_catch()
+    def log_gui(log_type_):
+        graph = bool(log_type_[0].get())
+        abbrev = bool(log_type_[1].get())
+        pretty = bool(log_type_[2].get())
         return abbrev, graph, pretty
         return abbrev, graph, pretty
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def reset_head_gui():
     def reset_head_gui():
         repo_head = head.get()
         repo_head = head.get()
         if repo_head == "":
         if repo_head == "":
@@ -455,6 +462,7 @@ class UIAPI:
         return repo_head, the_reset_type
         return repo_head, the_reset_type
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def reset_file_gui():
     def reset_file_gui():
         repo_head = head.get()
         repo_head = head.get()
         if repo_head == "":
         if repo_head == "":
@@ -462,12 +470,14 @@ class UIAPI:
         return repo_head
         return repo_head
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_new_branch_gui():
     def add_new_branch_gui():
         name = API.get_branch_name_gui()
         name = API.get_branch_name_gui()
         origin = origin_branch.get()
         origin = origin_branch.get()
         return name, origin
         return name, origin
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def branch_merge_gui():
     def branch_merge_gui():
         message = commit_message.get()
         message = commit_message.get()
         parameters_no_ff = not bool(no_fast_forward.get())  # 对于no_ff来说,True - 使用快速合并,所以要翻转
         parameters_no_ff = not bool(no_fast_forward.get())  # 对于no_ff来说,True - 使用快速合并,所以要翻转
@@ -480,32 +490,38 @@ class UIAPI:
         return message, name, parameters_no_ff
         return message, name, parameters_no_ff
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_branch_name_gui():
     def get_branch_name_gui():
         return branch_name.get()
         return branch_name.get()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_stash_gui():
     def get_stash_gui():
         stash_num = stash_name.get()
         stash_num = stash_name.get()
         return stash_num
         return stash_num
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_remote_gui():
     def add_remote_gui():
         ssh = remote_ssh.get()
         ssh = remote_ssh.get()
         name = remote_name.get()
         name = remote_name.get()
         return name, ssh
         return name, ssh
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def del_remote_gui():
     def del_remote_gui():
         name = remote_name.get()
         name = remote_name.get()
         return name
         return name
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def bind_remote_branch_gui():
     def bind_remote_branch_gui():
         remote = remote_branch.get()
         remote = remote_branch.get()
         local = local_branch.get()
         local = local_branch.get()
         return local, remote
         return local, remote
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def pull_push_gui():
     def pull_push_gui():
         branch = remote_branch.get()
         branch = remote_branch.get()
         remote = remote_name.get()
         remote = remote_name.get()
@@ -516,10 +532,12 @@ class UIAPI:
         return allow, branch, local, parameters_f, parameters_u, remote
         return allow, branch, local, parameters_f, parameters_u, remote
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_search_key_gui():
     def get_search_key_gui():
         return show_search_key.get()
         return show_search_key.get()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_tag_gui():
     def add_tag_gui():
         global tag_name, commit, tag_message
         global tag_name, commit, tag_message
         the_tag_name = tag_name.get()
         the_tag_name = tag_name.get()
@@ -528,6 +546,7 @@ class UIAPI:
         return the_tag_name, the_commit, the_tag_message
         return the_tag_name, the_commit, the_tag_message
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def push_tag_gui():
     def push_tag_gui():
         global tag_name
         global tag_name
         the_tag_name = tag_name.get()
         the_tag_name = tag_name.get()
@@ -535,28 +554,33 @@ class UIAPI:
         return remoto, the_tag_name
         return remoto, the_tag_name
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_remote_name_gui():
     def get_remote_name_gui():
         remoto = remote_name.get()
         remoto = remote_name.get()
         return remoto
         return remoto
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def del_remote_tag_gui():
     def del_remote_tag_gui():
         remoto = remote_name.get()
         remoto = remote_name.get()
         tag = tag_name.get()
         tag = tag_name.get()
         return remoto, tag
         return remoto, tag
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def del_remote_branch_gui():
     def del_remote_branch_gui():
         remote = remote_name.get()
         remote = remote_name.get()
         branch = remote_branch.get()
         branch = remote_branch.get()
         return branch, remote
         return branch, remote
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def del_tag_gui():
     def del_tag_gui():
         tag = tag_name.get()
         tag = tag_name.get()
         return tag
         return tag
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def featch_remote_gui():
     def featch_remote_gui():
         branch = remote_branch.get()
         branch = remote_branch.get()
         remote = remote_name.get()
         remote = remote_name.get()
@@ -564,6 +588,7 @@ class UIAPI:
         return branch, local, remote
         return branch, local, remote
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_customize_gui():
     def get_customize_gui():
         command = customize_input.get()
         command = customize_input.get()
         is_threaded_refresh = bool(threaded_refresh.get())
         is_threaded_refresh = bool(threaded_refresh.get())
@@ -571,12 +596,14 @@ class UIAPI:
         return command, is_asynchronous_display, is_threaded_refresh
         return command, is_asynchronous_display, is_threaded_refresh
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def clone_git_gui():
     def clone_git_gui():
         new_dir = askdirectory(title="选择仓库地址")
         new_dir = askdirectory(title="选择仓库地址")
         name = git.clone_repo(new_dir)
         name = git.clone_repo(new_dir)
         return name
         return name
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def branch_new_gui():
     def branch_new_gui():
         new_name = branch_new_name.get()
         new_name = branch_new_name.get()
         old_name = API.get_branch_name_gui()
         old_name = API.get_branch_name_gui()
@@ -585,31 +612,39 @@ class UIAPI:
 
 
 class API(UIAPI):
 class API(UIAPI):
     @staticmethod
     @staticmethod
+    @exception_catch()
     def branch_new():  # 克隆仓库
     def branch_new():  # 克隆仓库
         new_name, old_name = API.branch_new_gui()
         new_name, old_name = API.branch_new_gui()
         API.cli_gui(git.rename_branch, (API.get_repo_name_gui(), old_name, new_name), show_screen=False)
         API.cli_gui(git.rename_branch, (API.get_repo_name_gui(), old_name, new_name), show_screen=False)
         API.update_repo_box_gui()
         API.update_repo_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def clone_git():  # 克隆仓库
     def clone_git():  # 克隆仓库
         name = API.clone_git_gui()
         name = API.clone_git_gui()
         API.clone_core(name, clone_repo.get())
         API.clone_core(name, clone_repo.get())
         API.update_repo_box_gui()
         API.update_repo_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def clone_core(name, url):
     def clone_core(name, url):
-        API.cli_gui(
-            git.clone,
-            (name, url),
-            break_time=0,
-            tip_text=f"{url}:正在执行克隆操作",
-            is_threaded_refresh=True,
-            is_asynchronous_display=True,
-        )
-        git.after_clone(name)
-        API.update_git_file_last_gui()
+        try:
+            API.cli_gui(
+                git.clone,
+                (name, url),
+                break_time=0,
+                tip_text=f"{url}:正在执行克隆操作",
+                is_threaded_refresh=True,
+                is_asynchronous_display=True,
+            )
+            git.after_clone(name)
+        except BaseException:
+            raise
+        finally:
+            API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def customize():
     def customize():
         command, is_asynchronous_display, is_threaded_refresh = API.get_customize_gui()
         command, is_asynchronous_display, is_threaded_refresh = API.get_customize_gui()
         API.cli_gui(
         API.cli_gui(
@@ -623,6 +658,7 @@ class API(UIAPI):
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def fetch_remote():
     def fetch_remote():
         branch, local, remote = API.featch_remote_gui()
         branch, local, remote = API.featch_remote_gui()
         API.cli_gui(
         API.cli_gui(
@@ -636,12 +672,14 @@ class API(UIAPI):
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def del_tag():
     def del_tag():
         tag = API.del_tag_gui()
         tag = API.del_tag_gui()
         API.cli_gui(git.del_tag, (API.get_repo_name_gui(), tag))
         API.cli_gui(git.del_tag, (API.get_repo_name_gui(), tag))
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def del_remote_branch():
     def del_remote_branch():
         branch, remote = API.del_remote_branch_gui()
         branch, remote = API.del_remote_branch_gui()
         API.cli_gui(
         API.cli_gui(
@@ -655,6 +693,7 @@ class API(UIAPI):
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def del_remote_tag():
     def del_remote_tag():
         remoto, tag = API.del_remote_tag_gui()
         remoto, tag = API.del_remote_tag_gui()
         API.cli_gui(
         API.cli_gui(
@@ -668,6 +707,7 @@ class API(UIAPI):
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def push_all_tag():
     def push_all_tag():
         remoto = API.get_remote_name_gui()
         remoto = API.get_remote_name_gui()
         API.cli_gui(
         API.cli_gui(
@@ -681,6 +721,7 @@ class API(UIAPI):
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def push_tag():
     def push_tag():
         remoto, the_tag_name = API.push_tag_gui()
         remoto, the_tag_name = API.push_tag_gui()
         API.cli_gui(
         API.cli_gui(
@@ -694,6 +735,7 @@ class API(UIAPI):
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_tag():
     def add_tag():
         the_tag_name, the_commit, the_tag_message = API.add_tag_gui()
         the_tag_name, the_commit, the_tag_message = API.add_tag_gui()
         API.cli_gui(
         API.cli_gui(
@@ -702,6 +744,7 @@ class API(UIAPI):
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def show_tag(type_):
     def show_tag(type_):
         global git
         global git
         key = API.get_search_key_gui()
         key = API.get_search_key_gui()
@@ -712,6 +755,7 @@ class API(UIAPI):
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def pull_push_remote(type_):
     def pull_push_remote(type_):
         allow, branch, local, parameters_f, parameters_u, remote = API.pull_push_gui()
         allow, branch, local, parameters_f, parameters_u, remote = API.pull_push_gui()
         API.cli_gui(
         API.cli_gui(
@@ -727,30 +771,35 @@ class API(UIAPI):
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def bind_remote_branch():
     def bind_remote_branch():
         local, remote = API.bind_remote_branch_gui()
         local, remote = API.bind_remote_branch_gui()
         API.cli_gui(git.bind_branch, (API.get_repo_name_gui(), local, remote))
         API.cli_gui(git.bind_branch, (API.get_repo_name_gui(), local, remote))
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def del_remote():
     def del_remote():
         name = API.del_remote_gui()
         name = API.del_remote_gui()
         API.cli_gui(git.del_remote, (API.get_repo_name_gui(), name))
         API.cli_gui(git.del_remote, (API.get_repo_name_gui(), name))
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_remote():
     def add_remote():
         name, ssh = API.add_remote_gui()
         name, ssh = API.add_remote_gui()
         API.cli_gui(git.remote_add, (API.get_repo_name_gui(), ssh, name))
         API.cli_gui(git.remote_add, (API.get_repo_name_gui(), ssh, name))
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def cherry_pick():
     def cherry_pick():
         the_commit = API.get_commit_id_gui()
         the_commit = API.get_commit_id_gui()
         API.cli_gui(git.cherry_pick, (API.get_repo_name_gui(), the_commit))
         API.cli_gui(git.cherry_pick, (API.get_repo_name_gui(), the_commit))
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def open_stash(type_):
     def open_stash(type_):
         stash_num = API.get_stash_gui()
         stash_num = API.get_stash_gui()
         if stash_num == "":
         if stash_num == "":
@@ -759,24 +808,28 @@ class API(UIAPI):
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def branch_merge():
     def branch_merge():
         message, name, parameters_no_ff = API.branch_merge_gui()
         message, name, parameters_no_ff = API.branch_merge_gui()
         API.cli_gui(git.merge_branch, (API.get_repo_name_gui(), name, parameters_no_ff, message))
         API.cli_gui(git.merge_branch, (API.get_repo_name_gui(), name, parameters_no_ff, message))
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def del_branch(type_):
     def del_branch(type_):
         name = API.get_branch_name_gui()
         name = API.get_branch_name_gui()
         API.cli_gui(git.del_branch, (API.get_repo_name_gui(), name, type_))
         API.cli_gui(git.del_branch, (API.get_repo_name_gui(), name, type_))
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def switch_branch():
     def switch_branch():
         name = API.get_branch_name_gui()
         name = API.get_branch_name_gui()
         API.cli_gui(git.switch_branch, (API.get_repo_name_gui(), name), break_time=1, show_screen=False)
         API.cli_gui(git.switch_branch, (API.get_repo_name_gui(), name), break_time=1, show_screen=False)
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_new_branch():
     def add_new_branch():
         name, origin = API.add_new_branch_gui()
         name, origin = API.add_new_branch_gui()
         API.cli_gui(
         API.cli_gui(
@@ -785,6 +838,7 @@ class API(UIAPI):
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def remove_file():
     def remove_file():
         if not file_list:
         if not file_list:
             return False
             return False
@@ -792,6 +846,7 @@ class API(UIAPI):
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def checkout_file():  # 从暂存区、仓库返回文件
     def checkout_file():  # 从暂存区、仓库返回文件
         if not file_list:
         if not file_list:
             return False
             return False
@@ -799,18 +854,21 @@ class API(UIAPI):
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def reset_file():  # 使用reset回退文件
     def reset_file():  # 使用reset回退文件
         repo_head = API.reset_file_gui()
         repo_head = API.reset_file_gui()
         API.cli_gui(git.back_version_file, (API.get_repo_name_gui(), repo_head, file_list))
         API.cli_gui(git.back_version_file, (API.get_repo_name_gui(), repo_head, file_list))
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def reset_head():
     def reset_head():
         repo_head, the_reset_type = API.reset_head_gui()
         repo_head, the_reset_type = API.reset_head_gui()
         API.cli_gui(git.back_version, (API.get_repo_name_gui(), repo_head, the_reset_type))
         API.cli_gui(git.back_version, (API.get_repo_name_gui(), repo_head, the_reset_type))
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def log():
     def log():
         global git, log_type
         global git, log_type
         name = API.get_repo_name_gui()
         name = API.get_repo_name_gui()
@@ -819,6 +877,7 @@ class API(UIAPI):
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def not_parameters_call(func):
     def not_parameters_call(func):
         global git
         global git
         name = API.get_repo_name_gui()
         name = API.get_repo_name_gui()
@@ -826,18 +885,21 @@ class API(UIAPI):
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def commit_file():
     def commit_file():
         name = API.get_repo_name_gui()
         name = API.get_repo_name_gui()
         API.cli_gui(git.commit_file, (name, API.commit_file_gui()))
         API.cli_gui(git.commit_file, (name, API.commit_file_gui()))
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def diff():
     def diff():
         branch = API.diff_gui()
         branch = API.diff_gui()
         API.cli_gui(git.diff_file, (API.get_repo_name_gui(), branch))
         API.cli_gui(git.diff_file, (API.get_repo_name_gui(), branch))
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def remove_the_staging():
     def remove_the_staging():
         global git
         global git
         dic = file_list
         dic = file_list
@@ -847,6 +909,7 @@ class API(UIAPI):
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add():
     def add():
         dic = file_list
         dic = file_list
         if not dic:
         if not dic:
@@ -855,24 +918,28 @@ class API(UIAPI):
         API.update_git_file_last_gui()
         API.update_git_file_last_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_file_box_index():
     def get_file_box_index():
         return file_box.curselection()
         return file_box.curselection()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def del_file():
     def del_file():
         try:
         try:
             del file_list[API.get_file_box_index()]
             del file_list[API.get_file_box_index()]
             API.update_file_box_gui()
             API.update_file_box_gui()
-        except BaseException:
+        finally:
             pass
             pass
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def clean_file():
     def clean_file():
         global file_list
         global file_list
         file_list = []
         file_list = []
         API.update_file_box_gui()
         API.update_file_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def repo_init():  # 创建仓库
     def repo_init():  # 创建仓库
         global git
         global git
         new_dir = API.repo_init_gui()
         new_dir = API.repo_init_gui()

+ 17 - 26
gitrepo/template.py

@@ -37,8 +37,8 @@ class GitBase(metaclass=ABCMeta):
         code = ""
         code = ""
         for _ in range(8):  # 八位随机数
         for _ in range(8):  # 八位随机数
             code += passwd[random.randint(0, len(passwd) - 1)]  # 时间戳+8位随机数
             code += passwd[random.randint(0, len(passwd) - 1)]  # 时间戳+8位随机数
-        stop_key = (str(time()) + code).replace(".", "")
-        return stop_key
+        stop_key_ = (str(time()) + code).replace(".", "")
+        return stop_key_
 
 
     def get_flie_list(self, file_list, is_file=True, pat=" "):
     def get_flie_list(self, file_list, is_file=True, pat=" "):
         if file_list == ".":
         if file_list == ".":
@@ -70,9 +70,9 @@ class ViewClasses(GitBase, metaclass=ABCMeta):
             f"echo 删除... && {git_path} rm {file}", cwd=self.repo_dir, **sys_seeting
             f"echo 删除... && {git_path} rm {file}", cwd=self.repo_dir, **sys_seeting
         )
         )
 
 
-    def dir_list(self, all=True):
+    def dir_list(self, all_=True):
         listfile = []
         listfile = []
-        if all:
+        if all_:
             listfile += [
             listfile += [
                 f'[当前分支] {self.repo.active_branch} 工作区{"不" if self.repo.is_dirty() else ""}干净 -> {self.name}'
                 f'[当前分支] {self.repo.active_branch} 工作区{"不" if self.repo.is_dirty() else ""}干净 -> {self.name}'
             ]
             ]
@@ -250,10 +250,7 @@ class RemoveClass(GitBase, metaclass=ABCMeta):
 
 
     def del_branch_remote(self, remote, remote_branch):
     def del_branch_remote(self, remote, remote_branch):
         remote_split = remote.split("/")
         remote_split = remote.split("/")
-        try:
-            remote_name = remote_split[0]  # 获取主机名 1)
-        except BaseException:
-            remote_name = ""  # 没有主机名 1)
+        remote_name = remote_split[0]  # 获取主机名 1)
         branch_split = remote_branch.split("/")
         branch_split = remote_branch.split("/")
         if len(branch_split) >= 2 and remote_name == "":
         if len(branch_split) >= 2 and remote_name == "":
             remote_name = branch_split[0]  # 2)
             remote_name = branch_split[0]  # 2)
@@ -384,11 +381,8 @@ class RemoteClasses(GitBase, metaclass=ABCMeta):
         # 3) 如果local为空,用HEAD填充
         # 3) 如果local为空,用HEAD填充
         # 4) 如果以上后,主机名仍为空,则local和分支均为空
         # 4) 如果以上后,主机名仍为空,则local和分支均为空
 
 
-        split = remote.split("/")
-        try:
-            remote_name = split[0]  # 获取主机名 1)
-        except BaseException:
-            remote_name = ""  # 没有主机名 1)
+        split_ = remote.split("/")
+        remote_name = split_[0]  # 获取主机名 1)
 
 
         branch_split = remote_branch.split("/")
         branch_split = remote_branch.split("/")
         if len(branch_split) >= 2 and remote_name == "":
         if len(branch_split) >= 2 and remote_name == "":
@@ -432,11 +426,8 @@ class RemoteClasses(GitBase, metaclass=ABCMeta):
         # 3) 如果local为空,用HEAD填充
         # 3) 如果local为空,用HEAD填充
         # 4) 如果以上后,主机名仍为空,则local和分支均为空
         # 4) 如果以上后,主机名仍为空,则local和分支均为空
 
 
-        split = remote.split("/")
-        try:
-            remote_name = split[0]  # 获取主机名 1)
-        except BaseException:
-            remote_name = ""  # 没有主机名 1)
+        split_ = remote.split("/")
+        remote_name = split_[0]  # 获取主机名 1)
 
 
         branch_split = remote_branch.split("/")
         branch_split = remote_branch.split("/")
         if len(branch_split) >= 2 and remote_name == "":
         if len(branch_split) >= 2 and remote_name == "":
@@ -475,11 +466,11 @@ class GitRepo(ViewClasses, NewClasses, RemoveClass, BackClasses, ParallelClasses
         try:
         try:
             if exists(repo_dir + r"/.git"):  # 是否为git 仓库
             if exists(repo_dir + r"/.git"):  # 是否为git 仓库
                 pass
                 pass
-            elif repo_dir[-4:] == ".git":
+            elif repo_dir.endswith(".git"):
                 repo_dir = repo_dir[:-5]  # -5,得把/去掉
                 repo_dir = repo_dir[:-5]  # -5,得把/去掉
             else:
             else:
-                raise Exception
-        except BaseException:
+                assert True
+        except (AssertionError, IndexError):
             subprocess.Popen(
             subprocess.Popen(
                 f"{git_path} init", cwd=self.repo_dir, **sys_seeting
                 f"{git_path} init", cwd=self.repo_dir, **sys_seeting
             ).wait()
             ).wait()
@@ -495,14 +486,14 @@ class GitRepo(ViewClasses, NewClasses, RemoveClass, BackClasses, ParallelClasses
             **sys_seeting,
             **sys_seeting,
         )
         )
 
 
-    def make_dir(self, dir):
-        if len(dir) == "":
-            return dir
-        if dir[0].startswith(os.sep):
+    def make_dir(self, dir_):
+        if len(dir_) == "":
+            return dir_
+        if dir_[0].startswith(os.sep):
             inside = ""
             inside = ""
         else:
         else:
             inside = os.sep
             inside = os.sep
-        return self.repo_dir + inside + dir
+        return self.repo_dir + inside + dir_
 
 
 
 
 @plugin_class_loading(get_path(r'template/gitrepo'))
 @plugin_class_loading(get_path(r'template/gitrepo'))

+ 134 - 36
machinelearning/gui.py

@@ -8,6 +8,7 @@ import webbrowser
 
 
 import machinelearning.controller
 import machinelearning.controller
 import machinelearning.template
 import machinelearning.template
+from system import exception_catch
 
 
 calculation_list = []
 calculation_list = []
 calculation_method = []
 calculation_method = []
@@ -30,18 +31,21 @@ learn_dict = {}
 
 
 class UIAPI:
 class UIAPI:
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_split_shape_list_gui():
     def get_split_shape_list_gui():
         try:
         try:
             split_shape_list = eval(f"[{shape.get()}]", {})[0]
             split_shape_list = eval(f"[{shape.get()}]", {})[0]
-        except BaseException:
+        except IndexError:
             split_shape_list = 2
             split_shape_list = 2
         return split_shape_list
         return split_shape_list
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_reval_type_gui():
     def get_reval_type_gui():
         return processing_type.get()
         return processing_type.get()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_sheet_box_gui():
     def update_sheet_box_gui():
         global SCREEN, sheet_box, sheet_list
         global SCREEN, sheet_box, sheet_list
         sheet_list = list(learner_controller.get_form().keys())
         sheet_list = list(learner_controller.get_form().keys())
@@ -49,6 +53,7 @@ class UIAPI:
         sheet_box.insert(tkinter.END, *sheet_list)
         sheet_box.insert(tkinter.END, *sheet_list)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def creat_text_sheet_gui(data, name):
     def creat_text_sheet_gui(data, name):
         global bg_color
         global bg_color
         new_top = tkinter.Toplevel(bg=bg_color)
         new_top = tkinter.Toplevel(bg=bg_color)
@@ -61,6 +66,7 @@ class UIAPI:
         new_top.resizable(width=False, height=False)
         new_top.resizable(width=False, height=False)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_python_gui():
     def add_python_gui():
         python_dir = askopenfilename(
         python_dir = askopenfilename(
             title="选择载入的py", filetypes=[("Python", ".py"), ("Txt", ".txt")]
             title="选择载入的py", filetypes=[("Python", ".py"), ("Txt", ".txt")]
@@ -73,26 +79,25 @@ class UIAPI:
         return code, name
         return code, name
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_data_name_gui(get_from_box=True, is_x_data=True):  # 获得名字统一接口
     def get_data_name_gui(get_from_box=True, is_x_data=True):  # 获得名字统一接口
         global sheet_list, sheet_box, x_data
         global sheet_list, sheet_box, x_data
         if get_from_box:
         if get_from_box:
             try:
             try:
                 return sheet_list[sheet_box.curselection()[0]]
                 return sheet_list[sheet_box.curselection()[0]]
-            except BaseException:
+            except IndexError:
                 try:
                 try:
                     return sheet_list[0]
                     return sheet_list[0]
-                except BaseException:
+                except IndexError:
                     return None
                     return None
         else:
         else:
-            try:
-                if is_x_data:
-                    return x_data.get()
-                else:
-                    return y_data.get()
-            except BaseException:
-                return None
+            if is_x_data:
+                return x_data.get()
+            else:
+                return y_data.get()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_csv_gui():
     def add_csv_gui():
         csv_dir = askopenfilename(title="选择载入的CSV", filetypes=[("CSV", ".csv")])
         csv_dir = askopenfilename(title="选择载入的CSV", filetypes=[("CSV", ".csv")])
         the_sep = sep.get()
         the_sep = sep.get()
@@ -109,6 +114,7 @@ class UIAPI:
         return csv_dir, name, the_encoding, must_str, the_sep
         return csv_dir, name, the_encoding, must_str, the_sep
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def to_csv_gui():
     def to_csv_gui():
         save_dir = asksaveasfilename(title="选择保存的CSV", filetypes=[("CSV", ".csv")])
         save_dir = asksaveasfilename(title="选择保存的CSV", filetypes=[("CSV", ".csv")])
         csv_sep = sep.get()
         csv_sep = sep.get()
@@ -116,6 +122,7 @@ class UIAPI:
         return save_dir, name, csv_sep
         return save_dir, name, csv_sep
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_leaner_gui():
     def update_leaner_gui():
         global learn_dict, learner_box
         global learn_dict, learner_box
         learn_dict = learner_controller.return_learner()
         learn_dict = learner_controller.return_learner()
@@ -123,73 +130,83 @@ class UIAPI:
         learner_box.insert(tkinter.END, *learn_dict.keys())
         learner_box.insert(tkinter.END, *learn_dict.keys())
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def set_x_data_gui():
     def set_x_data_gui():
         global x_data
         global x_data
         x_data.set(API.get_data_name_gui())
         x_data.set(API.get_data_name_gui())
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def set_y_data_gui():
     def set_y_data_gui():
         global y_data
         global y_data
         y_data.set(API.get_data_name_gui())
         y_data.set(API.get_data_name_gui())
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def set_learner_gui():
     def set_learner_gui():
         global learner_output
         global learner_output
         learner_output.set(API.get_learner_gui(True))
         learner_output.set(API.get_learner_gui(True))
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_learner_gui(return_box=False):
     def get_learner_gui(return_box=False):
         global learn_dict, learner_box, learner_output
         global learn_dict, learner_box, learner_output
         if return_box:
         if return_box:
             try:
             try:
                 return list(learn_dict.keys())[learner_box.curselection()[0]]
                 return list(learn_dict.keys())[learner_box.curselection()[0]]
-            except BaseException:
+            except IndexError:
                 try:
                 try:
                     return list(learn_dict.keys)[0]
                     return list(learn_dict.keys)[0]
-                except BaseException:
+                except IndexError:
                     return API.get_learner_gui(False)
                     return API.get_learner_gui(False)
         else:
         else:
-            try:
-                return learner_output.get()
-            except BaseException:
-                return None
+            return learner_output.get()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def show_score_gui(message):
     def show_score_gui(message):
         tkinter.messagebox.showinfo("完成", message)
         tkinter.messagebox.showinfo("完成", message)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_learner_parameters_gui():
     def get_learner_parameters_gui():
         global learner_parameters
         global learner_parameters
         return learner_parameters.get("0.0", tkinter.END)
         return learner_parameters.get("0.0", tkinter.END)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_merge_box_index_gui():
     def get_merge_box_index_gui():
         return merge_box.curselection()[0]
         return merge_box.curselection()[0]
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_merge_box_gui():
     def update_merge_box_gui():
         global merge_list, merge_box
         global merge_list, merge_box
         merge_box.delete(0, tkinter.END)
         merge_box.delete(0, tkinter.END)
         merge_box.insert(tkinter.END, *merge_list)
         merge_box.insert(tkinter.END, *merge_list)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_merge_split_type_gui():
     def get_merge_split_type_gui():
         return processing_type.get()
         return processing_type.get()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_shape_gui():
     def get_shape_gui():
         return eval(f"[{shape.get()}]")[0]
         return eval(f"[{shape.get()}]")[0]
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def global_settings_gui():
     def global_settings_gui():
         return [bool(i.get()) for i in global_settings]
         return [bool(i.get()) for i in global_settings]
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_calculation_num_gui():
     def get_calculation_num_gui():
         return eval(value.get(), {})
         return eval(value.get(), {})
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def update_calculation_box_gui():
     def update_calculation_box_gui():
         global calculation_list, calculation_method, calculation_box
         global calculation_list, calculation_method, calculation_box
         calculation_box.delete(0, tkinter.END)
         calculation_box.delete(0, tkinter.END)
@@ -204,24 +221,29 @@ class UIAPI:
         )
         )
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def get_calculation_type_gui():
     def get_calculation_type_gui():
         return calculation_type.get()
         return calculation_type.get()
 
 
 
 
 class API(UIAPI):
 class API(UIAPI):
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_reverse_fast_fourier2():  # 添加Lenear的核心
     def add_reverse_fast_fourier2():  # 添加Lenear的核心
         API.add_leaner("[2]Reverse_Fast_Fourier")
         API.add_leaner("[2]Reverse_Fast_Fourier")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_reverse_fast_fourier():  # 添加Lenear的核心
     def add_reverse_fast_fourier():  # 添加Lenear的核心
         API.add_leaner("Reverse_Fast_Fourier")
         API.add_leaner("Reverse_Fast_Fourier")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_fast_fourier():  # 添加Lenear的核心
     def add_fast_fourier():  # 添加Lenear的核心
         API.add_leaner("Fast_Fourier")
         API.add_leaner("Fast_Fourier")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def curve_fitting():
     def curve_fitting():
         file_dir = askopenfilename(title="导入参数")
         file_dir = askopenfilename(title="导入参数")
         with open(file_dir, "r") as f:
         with open(file_dir, "r") as f:
@@ -229,18 +251,22 @@ class API(UIAPI):
             API.update_leaner_gui()
             API.update_leaner_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def show_clustering_score():
     def show_clustering_score():
         API.show_score(2)
         API.show_score(2)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def show_regression_score():
     def show_regression_score():
         API.show_score(1)
         API.show_score(1)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def show_class_score():
     def show_class_score():
         API.show_score(0)
         API.show_score(0)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def show_score(func):
     def show_score(func):
         learner = API.get_learner_gui(True)
         learner = API.get_learner_gui(True)
         save_dir = askdirectory(title="选择保存位置")
         save_dir = askdirectory(title="选择保存位置")
@@ -256,6 +282,7 @@ class API(UIAPI):
         API.update_sheet_box_gui()
         API.update_sheet_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def calculation():
     def calculation():
         global calculation_list, calculation_method
         global calculation_list, calculation_method
         func = API.get_calculation_type_gui()
         func = API.get_calculation_type_gui()
@@ -266,6 +293,7 @@ class API(UIAPI):
         API.update_sheet_box_gui()
         API.update_sheet_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_calculation_core(num, type_):
     def add_calculation_core(num, type_):
         if len(calculation_list) == 2:
         if len(calculation_list) == 2:
             del calculation_list[0]
             del calculation_list[0]
@@ -274,17 +302,20 @@ class API(UIAPI):
         calculation_method.append(type_)
         calculation_method.append(type_)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_calculation_number():
     def add_calculation_number():
         API.add_calculation_core(API.get_calculation_num_gui(), 0)
         API.add_calculation_core(API.get_calculation_num_gui(), 0)
         API.update_calculation_box_gui()
         API.update_calculation_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_calculation_object():
     def add_calculation_object():
         name = API.get_data_name_gui()
         name = API.get_data_name_gui()
         API.add_calculation_core(name, 1)
         API.add_calculation_core(name, 1)
         API.update_calculation_box_gui()
         API.update_calculation_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def del_leaner():
     def del_leaner():
         learn = API.get_learner_gui(True)
         learn = API.get_learner_gui(True)
         set_learne = API.get_learner_gui(False)  # 获取学习器Learner
         set_learne = API.get_learner_gui(False)  # 获取学习器Learner
@@ -293,31 +324,36 @@ class API(UIAPI):
         API.update_leaner_gui()
         API.update_leaner_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def global_seeting():
     def global_seeting():
         args = API.global_settings_gui()
         args = API.global_settings_gui()
         machinelearning.template.set_global(*args)
         machinelearning.template.set_global(*args)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def reshape():
     def reshape():
         numpy_shape = API.get_shape_gui()
         numpy_shape = API.get_shape_gui()
         learner_controller.reshape(API.get_data_name_gui(), numpy_shape)
         learner_controller.reshape(API.get_data_name_gui(), numpy_shape)
         API.update_sheet_box_gui()
         API.update_sheet_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def transpose():
     def transpose():
         try:
         try:
             func = API.get_shape_gui()
             func = API.get_shape_gui()
-        except BaseException:
+        except AssertionError:
             func = None
             func = None
         learner_controller.transpose(API.get_data_name_gui(), func)
         learner_controller.transpose(API.get_data_name_gui(), func)
         API.update_sheet_box_gui()
         API.update_sheet_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def del_ndim():
     def del_ndim():
         learner_controller.del_ndim(API.get_data_name_gui())
         learner_controller.del_ndim(API.get_data_name_gui())
         API.update_sheet_box_gui()
         API.update_sheet_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def reval():
     def reval():
         global learner_controller
         global learner_controller
         reval_type = API.get_reval_type_gui()
         reval_type = API.get_reval_type_gui()
@@ -325,12 +361,14 @@ class API(UIAPI):
         API.update_sheet_box_gui()
         API.update_sheet_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def two_split():
     def two_split():
         split_type = API.get_merge_split_type_gui()
         split_type = API.get_merge_split_type_gui()
         learner_controller.two_split(API.get_data_name_gui(), shape.get(), split_type)
         learner_controller.two_split(API.get_data_name_gui(), shape.get(), split_type)
         API.update_sheet_box_gui()
         API.update_sheet_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def split():
     def split():
         global learner_controller, shape
         global learner_controller, shape
         split_type = API.get_merge_split_type_gui()
         split_type = API.get_merge_split_type_gui()
@@ -339,6 +377,7 @@ class API(UIAPI):
         API.update_sheet_box_gui()
         API.update_sheet_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def merge():
     def merge():
         if len(merge_list) < 1:
         if len(merge_list) < 1:
             return False
             return False
@@ -347,16 +386,19 @@ class API(UIAPI):
         API.update_sheet_box_gui()
         API.update_sheet_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def merge_del():
     def merge_del():
         del merge_list[API.get_merge_box_index_gui()]
         del merge_list[API.get_merge_box_index_gui()]
         API.update_merge_box_gui()
         API.update_merge_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def merge_add():
     def merge_add():
         merge_list.append(API.get_data_name_gui())
         merge_list.append(API.get_data_name_gui())
         API.update_merge_box_gui()
         API.update_merge_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def visualization_results():
     def visualization_results():
         learner = API.get_learner_gui(True)
         learner = API.get_learner_gui(True)
         save_dir = askdirectory(title="选择保存位置")
         save_dir = askdirectory(title="选择保存位置")
@@ -366,6 +408,7 @@ class API(UIAPI):
         API.update_sheet_box_gui()
         API.update_sheet_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def score_learner():
     def score_learner():
         learner = API.get_learner_gui()
         learner = API.get_learner_gui()
         score = learner_controller.score(
         score = learner_controller.score(
@@ -374,6 +417,7 @@ class API(UIAPI):
         API.show_score_gui(f"针对测试数据评分结果为:{score}")
         API.show_score_gui(f"针对测试数据评分结果为:{score}")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def predict_learner():
     def predict_learner():
         learner = API.get_learner_gui()
         learner = API.get_learner_gui()
         data = learner_controller.predict(API.get_data_name_gui(False, True), learner)
         data = learner_controller.predict(API.get_data_name_gui(False, True), learner)
@@ -382,13 +426,13 @@ class API(UIAPI):
         API.update_sheet_box_gui()
         API.update_sheet_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def fit_learner():
     def fit_learner():
         learner = API.get_learner_gui()
         learner = API.get_learner_gui()
         try:
         try:
             split = float(data_split.get())
             split = float(data_split.get())
-            if split < 0 or 1 < split:
-                raise Exception
-        except BaseException:
+            assert split < 0 or 1 < split
+        except (AssertionError, ValueError):
             split = 0.3
             split = 0.3
         socore = learner_controller.fit_model(
         socore = learner_controller.fit_model(
             API.get_data_name_gui(False, True),
             API.get_data_name_gui(False, True),
@@ -403,18 +447,22 @@ class API(UIAPI):
         )
         )
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_statistics():  # 添加Lenear的核心
     def add_statistics():  # 添加Lenear的核心
         API.add_leaner("Statistics")
         API.add_leaner("Statistics")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_correlation():
     def add_correlation():
         API.add_leaner("Correlation")
         API.add_leaner("Correlation")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_matrix_scatter():
     def add_matrix_scatter():
         API.add_leaner("MatrixScatter")
         API.add_leaner("MatrixScatter")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_view_data():
     def add_view_data():
         learner_controller.add_view_data(
         learner_controller.add_view_data(
             API.get_learner_gui(), parameters=API.get_learner_parameters_gui()
             API.get_learner_gui(), parameters=API.get_learner_parameters_gui()
@@ -422,18 +470,22 @@ class API(UIAPI):
         API.update_leaner_gui()
         API.update_leaner_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_cluster_tree():
     def add_cluster_tree():
         API.add_leaner("ClusterTree")
         API.add_leaner("ClusterTree")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_feature_y_x():
     def add_feature_y_x():
         API.add_leaner("FeatureY-X")
         API.add_leaner("FeatureY-X")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_numpy_to_heatmap():
     def add_numpy_to_heatmap():
         API.add_leaner("HeatMap")
         API.add_leaner("HeatMap")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_predictive_heatmap_more():  # 添加Lenear的核心
     def add_predictive_heatmap_more():  # 添加Lenear的核心
         learner_controller.add_predictive_heat_map_more(
         learner_controller.add_predictive_heat_map_more(
             API.get_learner_gui(), parameters=API.get_learner_parameters_gui()
             API.get_learner_gui(), parameters=API.get_learner_parameters_gui()
@@ -441,6 +493,7 @@ class API(UIAPI):
         API.update_leaner_gui()
         API.update_leaner_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_predictive_heatmap():  # 添加Lenear的核心
     def add_predictive_heatmap():  # 添加Lenear的核心
         learner_controller.add_predictive_heat_map(
         learner_controller.add_predictive_heat_map(
             API.get_learner_gui(), parameters=API.get_learner_parameters_gui()
             API.get_learner_gui(), parameters=API.get_learner_parameters_gui()
@@ -448,190 +501,237 @@ class API(UIAPI):
         API.update_leaner_gui()
         API.update_leaner_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_feature_scatter_class_all():
     def add_feature_scatter_class_all():
         API.add_leaner("FeatureScatterClass_all")
         API.add_leaner("FeatureScatterClass_all")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_feature_scatter_all():
     def add_feature_scatter_all():
         API.add_leaner("FeatureScatter_all")
         API.add_leaner("FeatureScatter_all")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_feature_scatter_class():
     def add_feature_scatter_class():
         API.add_leaner("FeatureScatterClass")
         API.add_leaner("FeatureScatterClass")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_feature_scatter():
     def add_feature_scatter():
         API.add_leaner("FeatureScatter")
         API.add_leaner("FeatureScatter")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_class_bar():
     def add_class_bar():
         API.add_leaner("ClassBar")
         API.add_leaner("ClassBar")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_dbscan():
     def add_dbscan():
         API.add_leaner("DBSCAN")
         API.add_leaner("DBSCAN")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_agglomerative():
     def add_agglomerative():
         API.add_leaner("Agglomerative")
         API.add_leaner("Agglomerative")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_k_means():
     def add_k_means():
         API.add_leaner("k-means")
         API.add_leaner("k-means")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_mlp_class():
     def add_mlp_class():
         API.add_leaner("MLP_class")
         API.add_leaner("MLP_class")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_mlp():
     def add_mlp():
         API.add_leaner("MLP")
         API.add_leaner("MLP")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_svr():
     def add_svr():
         API.add_leaner("SVR")
         API.add_leaner("SVR")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_svc():
     def add_svc():
         API.add_leaner("SVC")
         API.add_leaner("SVC")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_gradient_tree():
     def add_gradient_tree():
         API.add_leaner("GradientTree")
         API.add_leaner("GradientTree")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_gradient_tree_class():
     def add_gradient_tree_class():
         API.add_leaner("GradientTree_class")
         API.add_leaner("GradientTree_class")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_tsne():
     def add_tsne():
         API.add_leaner("t-SNE")
         API.add_leaner("t-SNE")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_nmf():
     def add_nmf():
         API.add_leaner("NMF")
         API.add_leaner("NMF")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_lda():
     def add_lda():
         API.add_leaner("LDA")
         API.add_leaner("LDA")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_kpca():
     def add_kpca():
         API.add_leaner("KPCA")
         API.add_leaner("KPCA")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_rpca():
     def add_rpca():
         API.add_leaner("RPCA")
         API.add_leaner("RPCA")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_pca():
     def add_pca():
         API.add_leaner("PCA")
         API.add_leaner("PCA")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_missed():
     def add_missed():
         API.add_leaner("Missed")
         API.add_leaner("Missed")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_label():
     def add_label():
         API.add_leaner("Label")
         API.add_leaner("Label")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_one_hot_encoder():
     def add_one_hot_encoder():
         API.add_leaner("OneHotEncoder")
         API.add_leaner("OneHotEncoder")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_discretization():
     def add_discretization():
         API.add_leaner("Discretization")
         API.add_leaner("Discretization")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_binarizer():
     def add_binarizer():
         API.add_leaner("Binarizer")
         API.add_leaner("Binarizer")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_regularization():
     def add_regularization():
         API.add_leaner("Regularization")
         API.add_leaner("Regularization")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_fuzzy_quantization():
     def add_fuzzy_quantization():
         API.add_leaner("Fuzzy_quantization")
         API.add_leaner("Fuzzy_quantization")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_mapzoom():
     def add_mapzoom():
         API.add_leaner("Mapzoom")
         API.add_leaner("Mapzoom")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_sigmod_scaler():
     def add_sigmod_scaler():
         API.add_leaner("sigmodScaler")
         API.add_leaner("sigmodScaler")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_decimal_scaler():
     def add_decimal_scaler():
         API.add_leaner("decimalScaler")
         API.add_leaner("decimalScaler")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_atan_scaler():
     def add_atan_scaler():
         API.add_leaner("atanScaler")
         API.add_leaner("atanScaler")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_log_scaler():
     def add_log_scaler():
         API.add_leaner("LogScaler")
         API.add_leaner("LogScaler")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_min_max_scaler():
     def add_min_max_scaler():
         API.add_leaner("MinMaxScaler")
         API.add_leaner("MinMaxScaler")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_z_score():
     def add_z_score():
         API.add_leaner("Z-Score")
         API.add_leaner("Z-Score")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_forest():
     def add_forest():
         API.add_leaner("Forest")
         API.add_leaner("Forest")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_forest_class():
     def add_forest_class():
         API.add_leaner("Forest_class")
         API.add_leaner("Forest_class")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_tree_class():
     def add_tree_class():
         API.add_leaner("Tree_class")
         API.add_leaner("Tree_class")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_tree():
     def add_tree():
         API.add_leaner("Tree")
         API.add_leaner("Tree")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_select_k_best():
     def add_select_k_best():
         API.add_leaner("SelectKBest")
         API.add_leaner("SelectKBest")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_knn_class():
     def add_knn_class():
         API.add_leaner("Knn_class")
         API.add_leaner("Knn_class")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_logistic_regression():
     def add_logistic_regression():
         API.add_leaner("LogisticRegression")
         API.add_leaner("LogisticRegression")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_lasso():
     def add_lasso():
         API.add_leaner("Lasso")
         API.add_leaner("Lasso")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_variance():
     def add_variance():
         API.add_leaner("Variance")
         API.add_leaner("Variance")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_knn():
     def add_knn():
         API.add_leaner("Knn")
         API.add_leaner("Knn")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_ridge():
     def add_ridge():
         API.add_leaner("Ridge")
         API.add_leaner("Ridge")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_line():
     def add_line():
         API.add_leaner("Line")
         API.add_leaner("Line")
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_select_from_model():  # 添加Lenear的核心
     def add_select_from_model():  # 添加Lenear的核心
         learner_controller.add_select_from_model(
         learner_controller.add_select_from_model(
             API.get_learner_gui(), parameters=API.get_learner_parameters_gui()
             API.get_learner_gui(), parameters=API.get_learner_parameters_gui()
@@ -639,6 +739,7 @@ class API(UIAPI):
         API.update_leaner_gui()
         API.update_leaner_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_leaner(learner_type):  # 添加Lenear的核心
     def add_leaner(learner_type):  # 添加Lenear的核心
         learner_controller.add_learner(
         learner_controller.add_learner(
             learner_type, parameters=API.get_learner_parameters_gui()
             learner_type, parameters=API.get_learner_parameters_gui()
@@ -646,40 +747,37 @@ class API(UIAPI):
         API.update_leaner_gui()
         API.update_leaner_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def to_html_one():
     def to_html_one():
         html_dir = f"{PATH}{os.sep}$Show_Sheet.html"
         html_dir = f"{PATH}{os.sep}$Show_Sheet.html"
-        try:
-            name = API.get_data_name_gui()
-            if name is None:
-                raise Exception
-            learner_controller.to_html_one(name, html_dir)
-            webbrowser.open(html_dir)
-        except BaseException:
-            pass
+        name = API.get_data_name_gui()
+        assert name is None
+        learner_controller.to_html_one(name, html_dir)
+        webbrowser.open(html_dir)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def to_html():
     def to_html():
         html_dir = f"{PATH}{os.sep}$Show_Sheet.html"
         html_dir = f"{PATH}{os.sep}$Show_Sheet.html"
-        try:
-            name = API.get_data_name_gui()
-            if name is None:
-                raise Exception
-            learner_controller.to_html(name, html_dir, to_html_type.get())
-            webbrowser.open(html_dir)
-        except BaseException:
-            pass
+        name = API.get_data_name_gui()
+        assert name is None
+        learner_controller.to_html(name, html_dir, to_html_type.get())
+        webbrowser.open(html_dir)
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def to_csv():
     def to_csv():
         learner_controller.to_csv(*API.to_csv_gui())
         learner_controller.to_csv(*API.to_csv_gui())
         API.update_sheet_box_gui()
         API.update_sheet_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_csv():
     def add_csv():
         learner_controller.read_csv(*API.add_csv_gui())
         learner_controller.read_csv(*API.add_csv_gui())
         API.update_sheet_box_gui()
         API.update_sheet_box_gui()
 
 
     @staticmethod
     @staticmethod
+    @exception_catch()
     def add_python():
     def add_python():
         code, name = API.add_python_gui()
         code, name = API.add_python_gui()
         learner_controller.add_python(code, name)
         learner_controller.add_python(code, name)

+ 125 - 143
machinelearning/template.py

@@ -150,10 +150,7 @@ class LearnerIO(LearnBase):
         if isinstance(name["get"], np.array):
         if isinstance(name["get"], np.array):
             get = name["get"]
             get = name["get"]
         else:
         else:
-            try:
-                get = np.array(name["get"])
-            except BaseException:
-                get = np.array([name["get"]])
+            get = np.array(name["get"])
         self.add_form(get, sheet_name)
         self.add_form(get, sheet_name)
         return get
         return get
 
 
@@ -200,15 +197,15 @@ class LearnerIO(LearnBase):
         if html_type == 0:
         if html_type == 0:
 
 
             class NewTab(TabBase):
             class NewTab(TabBase):
-                def add(self, table, k, *f):
-                    self.tab.add(table, k)
+                def add(self, table_, k, *f):
+                    self.tab.add(table_, k)
 
 
             tab = NewTab(tab_First(page_title="CoTan:查看表格"))  # 一个Tab
             tab = NewTab(tab_First(page_title="CoTan:查看表格"))  # 一个Tab
         elif html_type == 1:
         elif html_type == 1:
 
 
             class NewTab(TabBase):
             class NewTab(TabBase):
-                def add(self, table, *k):
-                    self.tab.add(table)
+                def add(self, table_, *k):
+                    self.tab.add(table_)
 
 
             tab = NewTab(
             tab = NewTab(
                 Page(
                 Page(
@@ -217,8 +214,8 @@ class LearnerIO(LearnBase):
         else:
         else:
 
 
             class NewTab(TabBase):
             class NewTab(TabBase):
-                def add(self, table, *k):
-                    self.tab.add(table)
+                def add(self, table_, *k):
+                    self.tab.add(table_)
 
 
             tab = NewTab(
             tab = NewTab(
                 Page(
                 Page(
@@ -269,8 +266,8 @@ class LearnerSplit(LearnBase, metaclass=ABCMeta):
             if split < 1:
             if split < 1:
                 split = int(split * len(sheet) if axis == 1 else len(sheet[0]))
                 split = int(split * len(sheet) if axis == 1 else len(sheet[0]))
             else:
             else:
-                raise Exception
-        except BaseException:
+                assert True
+        except (ValueError, AssertionError):
             split = int(split)
             split = int(split)
         if axis == 0:
         if axis == 0:
             self.add_form(sheet[:, split:], f"{name[0]}分割")
             self.add_form(sheet[:, split:], f"{name[0]}分割")
@@ -371,10 +368,10 @@ class Machinebase(metaclass=ABCMeta):  # 学习器的基类
         return accuracy_score(y_really, y_predict)
         return accuracy_score(y_really, y_predict)
 
 
     @staticmethod
     @staticmethod
-    def _macro(y_predict, y_really):
+    def _macro(y_predict, y_really, func_num=0):
         func = [recall_score, precision_score, f1_score]  # 召回率,精确率和f1
         func = [recall_score, precision_score, f1_score]  # 召回率,精确率和f1
         class_ = np.unique(y_really).tolist()
         class_ = np.unique(y_really).tolist()
-        result = func[func](y_really, y_predict, class_, average=None)
+        result = func[func_num](y_really, y_predict, class_, average=None)
         return result, class_
         return result, class_
 
 
     @staticmethod
     @staticmethod
@@ -429,21 +426,19 @@ class StudyMachinebase(Machinebase):
     def fit_model(self, x_data, y_data, split=0.3, increment=True, **kwargs):
     def fit_model(self, x_data, y_data, split=0.3, increment=True, **kwargs):
         y_data = y_data.ravel()
         y_data = y_data.ravel()
         try:
         try:
-            if self.x_traindata is None or not increment:
-                raise Exception
-            self.x_traindata = np.vstack(x_data, self.x_traindata)
-            self.y_traindata = np.vstack(y_data, self.y_traindata)
-        except BaseException:
+            assert self.x_traindata is None or not increment
+            self.x_traindata = np.vstack((x_data, self.x_traindata))
+            self.y_traindata = np.vstack((y_data, self.y_traindata))
+        except (AssertionError, ValueError):
             self.x_traindata = x_data.copy()
             self.x_traindata = x_data.copy()
             self.y_traindata = y_data.copy()
             self.y_traindata = y_data.copy()
         x_train, x_test, y_train, y_test = train_test_split(
         x_train, x_test, y_train, y_test = train_test_split(
             x_data, y_data, test_size=split
             x_data, y_data, test_size=split
         )
         )
         try:  # 增量式训练
         try:  # 增量式训练
-            if not increment:
-                raise Exception
+            assert not increment
             self.model.partial_fit(x_data, y_data)
             self.model.partial_fit(x_data, y_data)
-        except BaseException:
+        except (AssertionError, AttributeError):
             self.model.fit(self.x_traindata, self.y_traindata)
             self.model.fit(self.x_traindata, self.y_traindata)
         train_score = self.model.score(x_train, y_train)
         train_score = self.model.score(x_train, y_train)
         test_score = self.model.score(x_test, y_test)
         test_score = self.model.score(x_test, y_test)
@@ -460,20 +455,20 @@ class StudyMachinebase(Machinebase):
 
 
         accuracy = self._accuracy(y_predict, y_really)
         accuracy = self._accuracy(y_predict, y_really)
 
 
-        recall, class_list = self._macro(y_predict, y_really)
-        precision, class_list = self._macro(y_predict, y_really)
-        f1, class_list = self._macro(y_predict, y_really)
+        recall, class_list = self._macro(y_predict, y_really, 0)
+        precision, class_list = self._macro(y_predict, y_really, 1)
+        f1, class_list = self._macro(y_predict, y_really, 2)
 
 
-        confusion_matrix, class_list = self._confusion_matrix(
+        confusion_matrix_, class_list = self._confusion_matrix(
             y_predict, y_really)
             y_predict, y_really)
         kappa = self._kappa_score(y_predict, y_really)
         kappa = self._kappa_score(y_predict, y_really)
         class_list: list
         class_list: list
         tab = Tab()
         tab = Tab()
 
 
-        def gauge_base(name: str, value: float) -> Gauge:
+        def gauge_base(name: str, value_: float) -> Gauge:
             c = (
             c = (
                 Gauge()
                 Gauge()
-                .add("", [(name, round(value * 100, 2))], min_=0, max_=100)
+                .add("", [(name, round(value_ * 100, 2))], min_=0, max_=100)
                 .set_global_opts(title_opts=opts.TitleOpts(title=name))
                 .set_global_opts(title_opts=opts.TitleOpts(title=name))
             )
             )
             return c
             return c
@@ -481,11 +476,11 @@ class StudyMachinebase(Machinebase):
         tab.add(gauge_base("准确率", accuracy), "准确率")
         tab.add(gauge_base("准确率", accuracy), "准确率")
         tab.add(gauge_base("kappa", kappa), "kappa")
         tab.add(gauge_base("kappa", kappa), "kappa")
 
 
-        def bar_base(name, value) -> Bar:
+        def bar_base(name, value_) -> Bar:
             c = (
             c = (
                 Bar()
                 Bar()
                 .add_xaxis(class_list)
                 .add_xaxis(class_list)
-                .add_yaxis(name, value, **label_setting)
+                .add_yaxis(name, value_, **label_setting)
                 .set_global_opts(
                 .set_global_opts(
                     title_opts=opts.TitleOpts(title=name), **global_setting
                     title_opts=opts.TitleOpts(title=name), **global_setting
                 )
                 )
@@ -496,14 +491,14 @@ class StudyMachinebase(Machinebase):
         tab.add(bar_base("召回率", recall.tolist()), "召回率")
         tab.add(bar_base("召回率", recall.tolist()), "召回率")
         tab.add(bar_base("F1", f1.tolist()), "F1")
         tab.add(bar_base("F1", f1.tolist()), "F1")
 
 
-        def heatmap_base(name, value, max_, min_, show) -> HeatMap:
+        def heatmap_base(name, value_, max_, min_, show) -> HeatMap:
             c = (
             c = (
                 HeatMap()
                 HeatMap()
                 .add_xaxis(class_list)
                 .add_xaxis(class_list)
                 .add_yaxis(
                 .add_yaxis(
                     name,
                     name,
                     class_list,
                     class_list,
-                    value,
+                    value_,
                     label_opts=opts.LabelOpts(is_show=show, position="inside"),
                     label_opts=opts.LabelOpts(is_show=show, position="inside"),
                 )
                 )
                 .set_global_opts(
                 .set_global_opts(
@@ -517,7 +512,7 @@ class StudyMachinebase(Machinebase):
             return c
             return c
 
 
         value = [
         value = [
-            [class_list[i], class_list[j], float(confusion_matrix[i, j])]
+            [class_list[i], class_list[j], float(confusion_matrix_[i, j])]
             for i in range(len(class_list))
             for i in range(len(class_list))
             for j in range(len(class_list))
             for j in range(len(class_list))
         ]
         ]
@@ -525,14 +520,14 @@ class StudyMachinebase(Machinebase):
             heatmap_base(
             heatmap_base(
                 "混淆矩阵",
                 "混淆矩阵",
                 value,
                 value,
-                float(confusion_matrix.max()),
-                float(confusion_matrix.min()),
+                float(confusion_matrix_.max()),
+                float(confusion_matrix_.min()),
                 len(class_list) < 7,
                 len(class_list) < 7,
             ),
             ),
             "混淆矩阵",
             "混淆矩阵",
         )
         )
 
 
-        des_to_csv(save_dir, "混淆矩阵", confusion_matrix, class_list, class_list)
+        des_to_csv(save_dir, "混淆矩阵", confusion_matrix_, class_list, class_list)
         des_to_csv(
         des_to_csv(
             save_dir, "评分", [
             save_dir, "评分", [
                 precision, recall, f1], class_list, [
                 precision, recall, f1], class_list, [
@@ -552,11 +547,11 @@ class StudyMachinebase(Machinebase):
 
 
         mse = self._mse(y_predict, y_really)
         mse = self._mse(y_predict, y_really)
         mae = self._mae(y_predict, y_really)
         mae = self._mae(y_predict, y_really)
-        r2_score = self._r2_score(y_predict, y_really)
+        r2_score_ = self._r2_score(y_predict, y_really)
         rmse = self._rmse(y_predict, y_really)
         rmse = self._rmse(y_predict, y_really)
 
 
         tab.add(make_tab(["MSE", "MAE", "RMSE", "r2_Score"], [
         tab.add(make_tab(["MSE", "MAE", "RMSE", "r2_Score"], [
-            [mse, mae, rmse, r2_score]]), "评估数据", )
+            [mse, mae, rmse, r2_score_]]), "评估数据", )
 
 
         save = save_dir + rf"{os.sep}回归模型评估.HTML"
         save = save_dir + rf"{os.sep}回归模型评估.HTML"
         tab.render(save)
         tab.render(save)
@@ -594,9 +589,9 @@ class StudyMachinebase(Machinebase):
 
 
         tab.add(gauge_base("平均轮廓系数", coefficient), "平均轮廓系数")
         tab.add(gauge_base("平均轮廓系数", coefficient), "平均轮廓系数")
 
 
-        def bar_(coefficient_array, name="数据轮廓系数"):
-            xaxis = [f"数据{i}" for i in range(len(coefficient_array))]
-            value = coefficient_array.tolist()
+        def bar_(coefficient_array_, name="数据轮廓系数"):
+            xaxis = [f"数据{i}" for i in range(len(coefficient_array_))]
+            value = coefficient_array_.tolist()
             tab.add(bar_base(name, value, xaxis), name)
             tab.add(bar_base(name, value, xaxis), name)
 
 
         n = 20
         n = 20
@@ -642,18 +637,16 @@ class PrepBase(StudyMachinebase):  # 不允许第二次训练
         if not self.have_predict:  # 不允许第二次训练
         if not self.have_predict:  # 不允许第二次训练
             y_data = y_data.ravel()
             y_data = y_data.ravel()
             try:
             try:
-                if self.x_traindata is None or not increment:
-                    raise Exception
-                self.x_traindata = np.vstack(x_data, self.x_traindata)
-                self.y_traindata = np.vstack(y_data, self.y_traindata)
-            except BaseException:
+                assert self.x_traindata is None or not increment
+                self.x_traindata = np.vstack((x_data, self.x_traindata))
+                self.y_traindata = np.vstack((y_data, self.y_traindata))
+            except (AssertionError, ValueError):
                 self.x_traindata = x_data.copy()
                 self.x_traindata = x_data.copy()
                 self.y_traindata = y_data.copy()
                 self.y_traindata = y_data.copy()
             try:  # 增量式训练
             try:  # 增量式训练
-                if not increment:
-                    raise Exception
+                assert not increment
                 self.model.partial_fit(x_data, y_data)
                 self.model.partial_fit(x_data, y_data)
-            except BaseException:
+            except (AssertionError, AttributeError):
                 self.model.fit(self.x_traindata, self.y_traindata)
                 self.model.fit(self.x_traindata, self.y_traindata)
         self.have_fit = True
         self.have_fit = True
         return "None", "None"
         return "None", "None"
@@ -674,16 +667,14 @@ class Unsupervised(PrepBase):  # 无监督,不允许第二次训练
         if not self.have_predict:  # 不允许第二次训练
         if not self.have_predict:  # 不允许第二次训练
             self.y_traindata = None
             self.y_traindata = None
             try:
             try:
-                if self.x_traindata is None or not increment:
-                    raise Exception
-                self.x_traindata = np.vstack(x_data, self.x_traindata)
-            except BaseException:
+                assert self.x_traindata is None or not increment
+                self.x_traindata = np.vstack((x_data, self.x_traindata))
+            except (AssertionError, ValueError):
                 self.x_traindata = x_data.copy()
                 self.x_traindata = x_data.copy()
             try:  # 增量式训练
             try:  # 增量式训练
-                if not increment:
-                    raise Exception
+                assert not increment
                 self.model.partial_fit(x_data)
                 self.model.partial_fit(x_data)
-            except BaseException:
+            except (AssertionError, AttributeError):
                 self.model.fit(self.x_traindata, self.y_traindata)
                 self.model.fit(self.x_traindata, self.y_traindata)
         self.have_fit = True
         self.have_fit = True
         return "None", "None"
         return "None", "None"
@@ -693,16 +684,15 @@ class UnsupervisedModel(PrepBase):  # 无监督
     def fit_model(self, x_data, increment=True, *args, **kwargs):
     def fit_model(self, x_data, increment=True, *args, **kwargs):
         self.y_traindata = None
         self.y_traindata = None
         try:
         try:
-            if self.x_traindata is None or not increment:
-                raise Exception
-            self.x_traindata = np.vstack(x_data, self.x_traindata)
-        except BaseException:
+            assert self.x_traindata is None or not increment
+            self.x_traindata = np.vstack((x_data, self.x_traindata))
+        except (AssertionError, ValueError):
             self.x_traindata = x_data.copy()
             self.x_traindata = x_data.copy()
         try:  # 增量式训练
         try:  # 增量式训练
             if not increment:
             if not increment:
                 raise Exception
                 raise Exception
             self.model.partial_fit(x_data)
             self.model.partial_fit(x_data)
-        except BaseException:
+        except (AssertionError, AttributeError):
             self.model.fit(self.x_traindata, self.y_traindata)
             self.model.fit(self.x_traindata, self.y_traindata)
         self.have_fit = True
         self.have_fit = True
         return "None", "None"
         return "None", "None"
@@ -784,13 +774,13 @@ class Corr(ToPyebase):  # 相关性和协方差
         corr: np.ndarray = data.corr().to_numpy()  # 相关性
         corr: np.ndarray = data.corr().to_numpy()  # 相关性
         cov: np.ndarray = data.cov().to_numpy()  # 协方差
         cov: np.ndarray = data.cov().to_numpy()  # 协方差
 
 
-        def heat_map(data, name: str, max_, min_):
-            x = [f"特征[{i}]" for i in range(len(data))]
-            y = [f"特征[{i}]" for i in range(len(data[0]))]
+        def heat_map(data_, name: str, max_, min_):
+            x = [f"特征[{i}]" for i in range(len(data_))]
+            y = [f"特征[{i}]" for i in range(len(data_[0]))]
             value = [
             value = [
-                (f"特征[{i}]", f"特征[{j}]", float(data[i][j]))
-                for i in range(len(data))
-                for j in range(len(data[i]))
+                (f"特征[{i}]", f"特征[{j}]", float(data_[i][j]))
+                for i in range(len(data_))
+                for j in range(len(data_[i]))
             ]
             ]
             c = (
             c = (
                 HeatMap()
                 HeatMap()
@@ -856,14 +846,14 @@ class ViewData(ToPyebase):  # 绘制预测型热力图
             x_testdata = self.x_testdata
             x_testdata = self.x_testdata
             if x_testdata is not None:
             if x_testdata is not None:
                 add_func(x_testdata, f"{x_name}:x测试数据")
                 add_func(x_testdata, f"{x_name}:x测试数据")
-        except BaseException:
+        finally:
             pass
             pass
 
 
         try:
         try:
             y_testdata = self.y_testdata.copy()
             y_testdata = self.y_testdata.copy()
             if y_testdata is not None:
             if y_testdata is not None:
                 add_func(y_testdata, f"{x_name}:y测试数据")
                 add_func(y_testdata, f"{x_name}:y测试数据")
-        except BaseException:
+        finally:
             pass
             pass
 
 
         self.have_fit = True
         self.have_fit = True
@@ -978,10 +968,9 @@ class ClassBar(ToPyebase):  # 类型柱状图
                         f"({iter_num})[{round(start, 2)}-"
                         f"({iter_num})[{round(start, 2)}-"
                         f"{round((start + n) if (start + n) <= end or not iter_num == 9 else end, 2)}]")
                         f"{round((start + n) if (start + n) <= end or not iter_num == 9 else end, 2)}]")
                     try:
                     try:
-                        if iter_num == 9:
-                            raise Exception  # 执行到第10次时,直接获取剩下的所有
+                        assert iter_num == 9  # 执行到第10次时,直接获取剩下的所有
                         s = (start <= i) == (i < end)  # 布尔索引
                         s = (start <= i) == (i < end)  # 布尔索引
-                    except BaseException:  # 因为start + n有超出end的风险
+                    except AssertionError:  # 因为start + n有超出end的风险
                         s = (start <= i) == (i <= end)  # 布尔索引
                         s = (start <= i) == (i <= end)  # 布尔索引
                     # n_data = i[s]  # 取得现在的特征数据
                     # n_data = i[s]  # 取得现在的特征数据
 
 
@@ -1100,7 +1089,7 @@ class PredictiveHeatmapBase(ToPyebase):  # 绘制预测型热力图
     def fit_model(self, x_data, *args, **kwargs):
     def fit_model(self, x_data, *args, **kwargs):
         try:
         try:
             self.means = x_data.ravel()
             self.means = x_data.ravel()
-        except BaseException:
+        finally:
             pass
             pass
         self.have_fit = True
         self.have_fit = True
         return "None", "None"
         return "None", "None"
@@ -1130,7 +1119,7 @@ class PredictiveHeatmapBase(ToPyebase):  # 绘制预测型热力图
                     if g == np.nan:
                     if g == np.nan:
                         raise Exception
                         raise Exception
                     x_means[i] = g
                     x_means[i] = g
-                except BaseException:
+                finally:
                     pass
                     pass
             get = decision_boundary_func(
             get = decision_boundary_func(
                 x_range, x_means, self.learner.predict, class_, data_type
                 x_range, x_means, self.learner.predict, class_, data_type
@@ -1142,7 +1131,7 @@ class PredictiveHeatmapBase(ToPyebase):  # 绘制预测型热力图
             data = class_ + [f"{i}" for i in x_means]
             data = class_ + [f"{i}" for i in x_means]
             c = Table().add(headers=heard, rows=[data])
             c = Table().add(headers=heard, rows=[data])
             tab.add(c, "数据表")
             tab.add(c, "数据表")
-        except BaseException:
+        except AttributeError:
             get, x_means, x_range, data_type = regress_visualization(x_data, y)
             get, x_means, x_range, data_type = regress_visualization(x_data, y)
 
 
             get = prediction_boundary_func(
             get = prediction_boundary_func(
@@ -1440,9 +1429,9 @@ class CategoricalData:  # 数据统计助手
                 self.x_means.append(np.mean(x1))
                 self.x_means.append(np.mean(x1))
                 self.add_range(x1)
                 self.add_range(x1)
             else:
             else:
-                raise Exception
+                assert True
             return x1_con
             return x1_con
-        except BaseException:  # 找出出现次数最多的元素
+        except TypeError:  # 找出出现次数最多的元素
             new = np.unique(x1)  # 去除相同的元素
             new = np.unique(x1)  # 去除相同的元素
             count_list = []
             count_list = []
             for i in new:
             for i in new:
@@ -1454,14 +1443,13 @@ class CategoricalData:  # 数据统计助手
 
 
     def add_range(self, x1: np.array, range_=True):
     def add_range(self, x1: np.array, range_=True):
         try:
         try:
-            if not range_:
-                raise Exception
+            assert not range_
             min_ = int(x1.min()) - 1
             min_ = int(x1.min()) - 1
             max_ = int(x1.max()) + 1
             max_ = int(x1.max()) + 1
             # 不需要复制列表
             # 不需要复制列表
             self.x_range.append([min_, max_])
             self.x_range.append([min_, max_])
             self.data_type.append(1)
             self.data_type.append(1)
-        except BaseException:
+        except AssertionError:
             self.x_range.append(list(set(x1.tolist())))  # 去除多余元素
             self.x_range.append(list(set(x1.tolist())))  # 去除多余元素
             self.data_type.append(2)
             self.data_type.append(2)
 
 
@@ -1877,7 +1865,7 @@ class SvcModel(StudyMachinebase):
         try:
         try:
             w_list = self.model.coef_.tolist()  # 未必有这个属性
             w_list = self.model.coef_.tolist()  # 未必有这个属性
             b = self.model.intercept_.tolist()
             b = self.model.intercept_.tolist()
-        except BaseException:
+        except AttributeError:
             w_list = []  # 未必有这个属性
             w_list = []  # 未必有这个属性
             b = []
             b = []
 
 
@@ -1957,7 +1945,7 @@ class SvrModel(StudyMachinebase):
         try:
         try:
             w_list = self.model.coef_.tolist()  # 未必有这个属性
             w_list = self.model.coef_.tolist()  # 未必有这个属性
             b = self.model.intercept_.tolist()
             b = self.model.intercept_.tolist()
-        except BaseException:
+        except AttributeError:
             w_list = []  # 未必有这个属性
             w_list = []  # 未必有这个属性
             b = []
             b = []
 
 
@@ -2156,7 +2144,7 @@ class SelectFromModel(PrepBase):  # 有监督
             for i in range(len(get)):
             for i in range(len(get)):
                 tab.add(get[i], f"[{i}]保留数据x-x散点图")
                 tab.add(get[i], f"[{i}]保留数据x-x散点图")
 
 
-        def make_bar(score):
+        def make_bar_(score):
             choose = []
             choose = []
             un_choose = []
             un_choose = []
             for i in range(len(score)):
             for i in range(len(score)):
@@ -2178,11 +2166,11 @@ class SelectFromModel(PrepBase):  # 有监督
             tab.add(c, "单变量重要程度")
             tab.add(c, "单变量重要程度")
 
 
         try:
         try:
-            make_bar(self.model.coef_)
-        except BaseException:
+            make_bar_(self.model.coef_)
+        except AttributeError:
             try:
             try:
-                make_bar(self.model.feature_importances_)
-            except BaseException:
+                make_bar_(self.model.feature_importances_)
+            finally:
                 pass
                 pass
 
 
         save = save_dir + rf"{os.sep}模型特征选择.HTML"
         save = save_dir + rf"{os.sep}模型特征选择.HTML"
@@ -2204,12 +2192,12 @@ class StandardizationModel(Unsupervised):  # z-score标准化 无监督
         x_data = self.x_testdata
         x_data = self.x_testdata
         var = self.model.var_.tolist()
         var = self.model.var_.tolist()
         means = self.model.mean_.tolist()
         means = self.model.mean_.tolist()
-        scale = self.model.scale_.tolist()
+        scale_ = self.model.scale_.tolist()
         conversion_control(y_data, x_data, tab)
         conversion_control(y_data, x_data, tab)
 
 
         make_bar("标准差", var, tab)
         make_bar("标准差", var, tab)
         make_bar("方差", means, tab)
         make_bar("方差", means, tab)
-        make_bar("Scale", scale, tab)
+        make_bar("Scale", scale_, tab)
 
 
         save = save_dir + rf"{os.sep}z-score标准化.HTML"
         save = save_dir + rf"{os.sep}z-score标准化.HTML"
         tab.render(save)  # 生成HTML
         tab.render(save)  # 生成HTML
@@ -2228,11 +2216,11 @@ class MinmaxscalerModel(Unsupervised):  # 离差标准化
         tab = Tab()
         tab = Tab()
         y_data = self.y_testdata
         y_data = self.y_testdata
         x_data = self.x_testdata
         x_data = self.x_testdata
-        scale = self.model.scale_.tolist()
+        scale_ = self.model.scale_.tolist()
         max_ = self.model.data_max_.tolist()
         max_ = self.model.data_max_.tolist()
         min_ = self.model.data_min_.tolist()
         min_ = self.model.data_min_.tolist()
         conversion_control(y_data, x_data, tab)
         conversion_control(y_data, x_data, tab)
-        make_bar("Scale", scale, tab)
+        make_bar("Scale", scale_, tab)
         tab.add(
         tab.add(
             make_tab(
             make_tab(
                 heard=[f"[{i}]特征最大值" for i in range(len(max_))]
                 heard=[f"[{i}]特征最大值" for i in range(len(max_))]
@@ -2264,7 +2252,7 @@ class LogscalerModel(PrepBase):  # 对数标准化
     def predict(self, x_data, *args, **kwargs):
     def predict(self, x_data, *args, **kwargs):
         try:
         try:
             max_logx = self.max_logx
             max_logx = self.max_logx
-        except BaseException:
+        except AttributeError:
             self.have_fit = False
             self.have_fit = False
             self.fit_model(x_data)
             self.fit_model(x_data)
             max_logx = self.max_logx
             max_logx = self.max_logx
@@ -2336,7 +2324,7 @@ class DecimalscalerModel(PrepBase):  # 小数定标准化
         self.x_testdata = x_data.copy()
         self.x_testdata = x_data.copy()
         try:
         try:
             j = self.j
             j = self.j
-        except BaseException:
+        except AttributeError:
             self.have_fit = False
             self.have_fit = False
             self.fit_model(x_data)
             self.fit_model(x_data)
             j = self.j
             j = self.j
@@ -2379,7 +2367,7 @@ class MapzoomModel(PrepBase):  # 映射标准化
         try:
         try:
             max_ = self.max_
             max_ = self.max_
             min_ = self.min_
             min_ = self.min_
-        except BaseException:
+        except AttributeError:
             self.have_fit = False
             self.have_fit = False
             self.fit_model(x_data)
             self.fit_model(x_data)
             max_ = self.max_
             max_ = self.max_
@@ -2456,7 +2444,7 @@ class FuzzyQuantizationModel(PrepBase):  # 模糊量化标准化
         try:
         try:
             max_ = self.max_
             max_ = self.max_
             min_ = self.max_
             min_ = self.max_
-        except BaseException:
+        except AttributeError:
             self.have_fit = False
             self.have_fit = False
             self.fit_model(x_data)
             self.fit_model(x_data)
             max_ = self.max_
             max_ = self.max_
@@ -2562,7 +2550,7 @@ class DiscretizationModel(PrepBase):  # n值离散
         for i in range(len(range_)):
         for i in range(len(range_)):
             try:
             try:
                 t = float(range_[i])
                 t = float(range_[i])
-            except BaseException:
+            except ValueError:
                 continue
                 continue
             if o_t is None:  # 第一个参数
             if o_t is None:  # 第一个参数
                 bool_list.append(x_predict <= t)
                 bool_list.append(x_predict <= t)
@@ -3007,7 +2995,7 @@ class NmfModel(Unsupervised):
         wh_data = np.matmul(y_data, h_data)
         wh_data = np.matmul(y_data, h_data)
         difference_data = x_data - wh_data
         difference_data = x_data - wh_data
 
 
-        def make_heat_map(data, name, max_, min_):
+        def make_heat_map(data, name, data_max, data_min):
             x = [f"数据[{i}]" for i in range(len(data))]  # 主成分
             x = [f"数据[{i}]" for i in range(len(data))]  # 主成分
             y = [f"特征[{i}]" for i in range(len(data[0]))]  # 主成分
             y = [f"特征[{i}]" for i in range(len(data[0]))]  # 主成分
             value = [
             value = [
@@ -3028,7 +3016,7 @@ class NmfModel(Unsupervised):
                     ),  # 'category'
                     ),  # 'category'
                     xaxis_opts=opts.AxisOpts(is_scale=True, type_="category"),
                     xaxis_opts=opts.AxisOpts(is_scale=True, type_="category"),
                     visualmap_opts=opts.VisualMapOpts(
                     visualmap_opts=opts.VisualMapOpts(
-                        is_show=True, max_=max_, min_=min_, pos_right="3%"
+                        is_show=True, max_=data_max, min_=data_min, pos_right="3%"
                     ),
                     ),
                 )  # 显示
                 )  # 显示
             )
             )
@@ -3118,13 +3106,13 @@ class MlpModel(StudyMachinebase):  # 神经网络(多层感知机),有监督
         class_ = self.model.classes_
         class_ = self.model.classes_
         n_layers_ = self.model.n_layers_
         n_layers_ = self.model.n_layers_
 
 
-        def make_heat_map(data, name):
-            x = [f"特征(节点)[{i}]" for i in range(len(data))]
-            y = [f"节点[{i}]" for i in range(len(data[0]))]
+        def make_heat_map(data_, name):
+            x = [f"特征(节点)[{i}]" for i in range(len(data_))]
+            y = [f"节点[{i}]" for i in range(len(data_[0]))]
             value = [
             value = [
-                (f"特征(节点)[{i}]", f"节点[{j}]", float(data[i][j]))
-                for i in range(len(data))
-                for j in range(len(data[i]))
+                (f"特征(节点)[{i}]", f"节点[{j}]", float(data_[i][j]))
+                for i in range(len(data_))
+                for j in range(len(data_[i]))
             ]
             ]
 
 
             c = (
             c = (
@@ -3140,15 +3128,15 @@ class MlpModel(StudyMachinebase):  # 神经网络(多层感知机),有监督
                     xaxis_opts=opts.AxisOpts(is_scale=True, type_="category"),
                     xaxis_opts=opts.AxisOpts(is_scale=True, type_="category"),
                     visualmap_opts=opts.VisualMapOpts(
                     visualmap_opts=opts.VisualMapOpts(
                         is_show=True,
                         is_show=True,
-                        max_=float(data.max()),
-                        min_=float(data.min()),
+                        max_=float(data_.max()),
+                        min_=float(data_.min()),
                         pos_right="3%",
                         pos_right="3%",
                     ),
                     ),
                 )  # 显示
                 )  # 显示
             )
             )
             tab.add(c, name)
             tab.add(c, name)
-            tab.add(make_tab(x, data.transpose().tolist()), f"{name}:表格")
-            des_to_csv(save_dir, f"{name}:表格", data.transpose().tolist(), x, y)
+            tab.add(make_tab(x, data_.transpose().tolist()), f"{name}:表格")
+            des_to_csv(save_dir, f"{name}:表格", data_.transpose().tolist(), x, y)
 
 
         get, x_means, x_range, data_type = regress_visualization(
         get, x_means, x_range, data_type = regress_visualization(
             x_data, y_data)
             x_data, y_data)
@@ -3189,10 +3177,10 @@ class KmeansModel(UnsupervisedModel):
         self.model_Name = "k-means"
         self.model_Name = "k-means"
 
 
     def fit_model(self, x_data, *args, **kwargs):
     def fit_model(self, x_data, *args, **kwargs):
-        re = super().fit_model(x_data, *args, **kwargs)
+        return_ = super().fit_model(x_data, *args, **kwargs)
         self.class_ = list(set(self.model.labels_.tolist()))
         self.class_ = list(set(self.model.labels_.tolist()))
         self.have_fit = True
         self.have_fit = True
-        return re
+        return return_
 
 
     def predict(self, x_data, *args, **kwargs):
     def predict(self, x_data, *args, **kwargs):
         self.x_testdata = x_data.copy()
         self.x_testdata = x_data.copy()
@@ -3256,10 +3244,10 @@ class AgglomerativeModel(UnsupervisedModel):
         self.model_Name = "Agglomerative"
         self.model_Name = "Agglomerative"
 
 
     def fit_model(self, x_data, *args, **kwargs):
     def fit_model(self, x_data, *args, **kwargs):
-        re = super().fit_model(x_data, *args, **kwargs)
+        return_ = super().fit_model(x_data, *args, **kwargs)
         self.class_ = list(set(self.model.labels_.tolist()))
         self.class_ = list(set(self.model.labels_.tolist()))
         self.have_fit = True
         self.have_fit = True
-        return re
+        return return_
 
 
     def predict(self, x_data, *args, **kwargs):
     def predict(self, x_data, *args, **kwargs):
         self.x_testdata = x_data.copy()
         self.x_testdata = x_data.copy()
@@ -3338,10 +3326,10 @@ class DbscanModel(UnsupervisedModel):
         self.model_Name = "DBSCAN"
         self.model_Name = "DBSCAN"
 
 
     def fit_model(self, x_data, *args, **kwargs):
     def fit_model(self, x_data, *args, **kwargs):
-        re = super().fit_model(x_data, *args, **kwargs)
+        return_ = super().fit_model(x_data, *args, **kwargs)
         self.class_ = list(set(self.model.labels_.tolist()))
         self.class_ = list(set(self.model.labels_.tolist()))
         self.have_fit = True
         self.have_fit = True
-        return re
+        return return_
 
 
     def predict(self, x_data, *args, **kwargs):
     def predict(self, x_data, *args, **kwargs):
         self.x_testdata = x_data.copy()
         self.x_testdata = x_data.copy()
@@ -3397,10 +3385,9 @@ class FastFourier(StudyMachinebase):  # 快速傅里叶变换
     def fit_model(self, y_data, *args, **kwargs):
     def fit_model(self, y_data, *args, **kwargs):
         y_data = y_data.ravel()  # 扯平为一维数组
         y_data = y_data.ravel()  # 扯平为一维数组
         try:
         try:
-            if self.y_traindata is None:
-                raise Exception
-            self.y_traindata = np.hstack(y_data, self.x_traindata)
-        except BaseException:
+            assert self.y_traindata is None
+            self.y_traindata = np.hstack((y_data, self.x_traindata))
+        except (AssertionError, ValueError):
             self.y_traindata = y_data.copy()
             self.y_traindata = y_data.copy()
         fourier = fft(y_data)
         fourier = fft(y_data)
         self.sample_size = len(y_data)
         self.sample_size = len(y_data)
@@ -3597,11 +3584,10 @@ def FUNC({",".join(model.__code__.co_varnames)}):
         y_data = y_data.ravel()
         y_data = y_data.ravel()
         x_data = x_data.astype(np.float64)
         x_data = x_data.astype(np.float64)
         try:
         try:
-            if self.x_traindata is None:
-                raise Exception
-            self.x_traindata = np.vstack(x_data, self.x_traindata)
-            self.y_traindata = np.vstack(y_data, self.y_traindata)
-        except BaseException:
+            assert self.x_traindata is None
+            self.x_traindata = np.vstack((x_data, self.x_traindata))
+            self.y_traindata = np.vstack((y_data, self.y_traindata))
+        except (AssertionError, ValueError):
             self.x_traindata = x_data.copy()
             self.x_traindata = x_data.copy()
             self.y_traindata = y_data.copy()
             self.y_traindata = y_data.copy()
         self.fit_data = optimize.curve_fit(
         self.fit_data = optimize.curve_fit(
@@ -3706,7 +3692,7 @@ class Table(TableFisrt):
                 DataFrame(self.ROWS, columns=self.HEADERS).to_csv(
                 DataFrame(self.ROWS, columns=self.HEADERS).to_csv(
                     save_dir + os.sep + name + ".csv"
                     save_dir + os.sep + name + ".csv"
                 )
                 )
-            except BaseException:
+            finally:
                 pass
                 pass
         return super().render(path, *args, **kwargs)
         return super().render(path, *args, **kwargs)
 
 
@@ -3716,14 +3702,14 @@ def make_list(first, end, num=35):
     n = num / (end - first)
     n = num / (end - first)
     if n == 0:
     if n == 0:
         n = 1
         n = 1
-    re = []
+    return_ = []
     n_first = first * n
     n_first = first * n
     n_end = end * n
     n_end = end * n
     while n_first <= n_end:
     while n_first <= n_end:
         cul = n_first / n
         cul = n_first / n
-        re.append(round(cul, 2))
+        return_.append(round(cul, 2))
         n_first += 1
         n_first += 1
-    return re
+    return return_
 
 
 
 
 @plugin_func_loading(get_path(r"template/machinelearning"))
 @plugin_func_loading(get_path(r"template/machinelearning"))
@@ -3731,8 +3717,8 @@ def list_filter(original_list, num=70):
     if len(original_list) <= num:
     if len(original_list) <= num:
         return original_list
         return original_list
     n = int(num / len(original_list))
     n = int(num / len(original_list))
-    re = original_list[::n]
-    return re
+    return_ = original_list[::n]
+    return return_
 
 
 
 
 @plugin_func_loading(get_path(r"template/machinelearning"))
 @plugin_func_loading(get_path(r"template/machinelearning"))
@@ -4039,7 +4025,7 @@ def see_tree(tree_file_dir):
                 if regex_result[0] != "":
                 if regex_result[0] != "":
                     try:
                     try:
                         v = float(regex_result[0])
                         v = float(regex_result[0])
-                    except BaseException:
+                    except ValueError:
                         v = 0
                         v = 0
                     node_dict[regex_result[0]] = {
                     node_dict[regex_result[0]] = {
                         "name": regex_result[1].replace("\\n", "\n"),
                         "name": regex_result[1].replace("\\n", "\n"),
@@ -4047,13 +4033,13 @@ def see_tree(tree_file_dir):
                         "children": [],
                         "children": [],
                     }
                     }
                     continue
                     continue
-            except BaseException:
+            finally:
                 pass
                 pass
             try:
             try:
                 regex_result = re.findall(link_regex, i)[0]
                 regex_result = re.findall(link_regex, i)[0]
                 if regex_result[0] != "" and regex_result[1] != "":
                 if regex_result[0] != "" and regex_result[1] != "":
                     link_list.append((regex_result[0], regex_result[1]))
                     link_list.append((regex_result[0], regex_result[1]))
-            except BaseException:
+            finally:
                 pass
                 pass
 
 
     father_list = []  # 已经有父亲的list
     father_list = []  # 已经有父亲的list
@@ -4063,7 +4049,7 @@ def see_tree(tree_file_dir):
         try:
         try:
             node_dict[father]["children"].append(node_dict[son])
             node_dict[father]["children"].append(node_dict[son])
             father_list.append(son)
             father_list.append(son)
-        except BaseException:
+        finally:
             pass
             pass
 
 
     father = list(set(node_dict.keys()) - set(father_list))
     father = list(set(node_dict.keys()) - set(father_list))
@@ -4111,11 +4097,7 @@ def coefficient_bar_plot(w_heard, w):
 def is_continuous(data: np.array, f: float = 0.1):
 def is_continuous(data: np.array, f: float = 0.1):
     data = data.tolist()
     data = data.tolist()
     l: list = np.unique(data).tolist()
     l: list = np.unique(data).tolist()
-    try:
-        re = len(l) / len(data) >= f or len(data) <= 3
-        return re
-    except BaseException:
-        return False
+    return len(l) / len(data) >= f or len(data) <= 3
 
 
 
 
 @plugin_func_loading(get_path(r"template/machinelearning"))
 @plugin_func_loading(get_path(r"template/machinelearning"))
@@ -4226,7 +4208,7 @@ def training_visualization_more(x_data, class_list, y_data, center):
                 # 添加簇中心
                 # 添加簇中心
                 try:
                 try:
                     center_x2 = [center[class_num][a]]
                     center_x2 = [center[class_num][a]]
-                except BaseException:
+                except IndexError:
                     center_x2 = [0]
                     center_x2 = [0]
                 b = (
                 b = (
                     Scatter()
                     Scatter()
@@ -4305,7 +4287,7 @@ def training_visualization_center(x_data, class_data, y_data, center):
             # 添加簇中心
             # 添加簇中心
             try:
             try:
                 center_x_2 = [center[class_num][i - 1]]
                 center_x_2 = [center[class_num][i - 1]]
-            except BaseException:
+            except IndexError:
                 center_x_2 = [0]
                 center_x_2 = [0]
             b = (
             b = (
                 Scatter() .add_xaxis(center_x_2) .add_yaxis(
                 Scatter() .add_xaxis(center_x_2) .add_yaxis(
@@ -4548,7 +4530,7 @@ def regress_visualization(x_data, y_data):  # y-x数据图
             min_=int(y_data.min()),
             min_=int(y_data.min()),
             pos_right="3%",
             pos_right="3%",
         )
         )
-    except BaseException:
+    except ValueError:
         visualmap_opts = None
         visualmap_opts = None
         y_is_continuous = False
         y_is_continuous = False
     for i in range(len(x_data)):
     for i in range(len(x_data)):
@@ -4811,7 +4793,7 @@ def pack(output_filename, source_dir):
 
 
 def set_global(
 def set_global(
     more=more_global,
     more=more_global,
-    all=all_global,
+    all_=all_global,
     csv=csv_global,
     csv=csv_global,
     clf=clf_global,
     clf=clf_global,
     tar=tar_global,
     tar=tar_global,
@@ -4819,7 +4801,7 @@ def set_global(
 ):
 ):
     global more_global, all_global, csv_global, clf_global, tar_global, new_dir_global
     global more_global, all_global, csv_global, clf_global, tar_global, new_dir_global
     more_global = more  # 是否使用全部特征绘图
     more_global = more  # 是否使用全部特征绘图
-    all_global = all  # 是否导出charts
+    all_global = all_  # 是否导出charts
     csv_global = csv  # 是否导出CSV
     csv_global = csv  # 是否导出CSV
     clf_global = clf  # 是否导出模型
     clf_global = clf  # 是否导出模型
     tar_global = tar  # 是否打包tar
     tar_global = tar  # 是否打包tar

+ 13 - 0
pip_insatall/pip_install

@@ -1,19 +1,32 @@
 CoTan  pip install dependencies:
 CoTan  pip install dependencies:
 
 
+# 图像处理
 Pillow==7.0.0
 Pillow==7.0.0
+# 草稿板
 pygame==1.9.6
 pygame==1.9.6
+# 自动化网页依赖
 selenium==3.141.0
 selenium==3.141.0
+# 网络爬虫
 requests==2.22.0
 requests==2.22.0
 bs4==0.0.1
 bs4==0.0.1
 urllib3==1.24.3
 urllib3==1.24.3
+# git版本控制
 Gitpython==3.1.0
 Gitpython==3.1.0
+# 矩阵
 numpy==1.18.1
 numpy==1.18.1
+# 表格
 pandas==0.25.3
 pandas==0.25.3
+# 输出表格信息(依赖于pandas)
 pandas-profiling==2.5.0
 pandas-profiling==2.5.0
+# 稀疏矩阵、数据科学
 scipy==1.4.1
 scipy==1.4.1
+# 符号数学
 sympy==1.5.1
 sympy==1.5.1
+# 学术性绘图
 matplotlib
 matplotlib
+# 美观性绘图
 pyecharts==1.7.0
 pyecharts==1.7.0
+# 机器学习
 sklearn(sciket-learn==0.22.2.post1)==0.0
 sklearn(sciket-learn==0.22.2.post1)==0.0
 pip==20.0.2
 pip==20.0.2
 
 

+ 27 - 3
system/__init__.py

@@ -1,10 +1,18 @@
 import os
 import os
+import logging
 
 
 PATH = os.getcwd()
 PATH = os.getcwd()
+LOG_DIR = rf'{PATH}{os.sep}Log{os.sep}log_system.log'
+LOG_FORMAT = '%(asctime)s - %(pathname)s - [%(lineno)d]%(funcName)s  %(message)s'
+logging.basicConfig(filename=LOG_DIR, level=logging.DEBUG, format=LOG_FORMAT)
+
+
+class NoPluginError(Exception):
+    pass
 
 
 
 
 def get_path(name):
 def get_path(name):
-    return f'{PATH}/{name}'
+    return f'{PATH}{os.sep}{name}'
 
 
 
 
 def plugin_class_loading(template_path):
 def plugin_class_loading(template_path):
@@ -19,10 +27,26 @@ def plugin_class_loading(template_path):
                     exec(f.read().replace('base = None', ''), namespace)
                     exec(f.read().replace('base = None', ''), namespace)
                 return namespace[name]
                 return namespace[name]
             else:
             else:
-                raise Exception
-        except BaseException:
+                raise NoPluginError
+        except NoPluginError as e:
+            logging.info(str(e) + 'no plugin')
+            return base
+        except BaseException as e:
+            logging.warning(str(e))
             return base
             return base
     return plugin_read
     return plugin_read
 
 
 
 
 plugin_func_loading = plugin_class_loading
 plugin_func_loading = plugin_class_loading
+
+
+def exception_catch(*args_catch, **kwargs_catch):
+    def catch(func):
+        def adorner(*args, **kwargs):
+            try:
+                func()
+            except BaseException as e:
+                logging.error(str(e))
+                assert func.__name__.endswith('_gui'), str(e)
+        return adorner
+    return catch

+ 2 - 3
system/controller.py

@@ -27,10 +27,9 @@ class Plugin:
         for name in self.dir_list:
         for name in self.dir_list:
             try:
             try:
                 plugin = os.listdir(f'{PATH}{os.sep}{name}')
                 plugin = os.listdir(f'{PATH}{os.sep}{name}')
-            except BaseException:
-                pass
-            else:
                 self.plugin_list += [f'{name}{os.sep}{i}' for i in plugin]
                 self.plugin_list += [f'{name}{os.sep}{i}' for i in plugin]
+            finally:
+                pass
         return self.plugin_list.copy()
         return self.plugin_list.copy()
 
 
     def get_plugin(self, index):
     def get_plugin(self, index):

+ 6 - 8
system/gui.py

@@ -78,8 +78,8 @@ def add_plugin():
     except ConflictError:
     except ConflictError:
         if askokcancel("提示", f"已经存在插件,是否需要尝试合并插件?\n[合并失败将产生不可逆的后果]"):
         if askokcancel("提示", f"已经存在插件,是否需要尝试合并插件?\n[合并失败将产生不可逆的后果]"):
             plugin.merge_plugin(index, plugin_dir)
             plugin.merge_plugin(index, plugin_dir)
-    except BaseException:
-        showwarning("文件错误", "插件导入遇到了未知错误")
+    except BaseException as e:
+        showwarning("文件错误", f"插件导入遇到了未知错误:\n{e}")
     else:
     else:
         plugin_box.delete(0, tkinter.END)
         plugin_box.delete(0, tkinter.END)
         plugin_box.insert(0, *plugin_list)
         plugin_box.insert(0, *plugin_list)
@@ -89,21 +89,19 @@ def del_plugin():
     index = plugin_box.curselection()[0]
     index = plugin_box.curselection()[0]
     try:
     try:
         plugin_list = plugin.del_plugin(index)
         plugin_list = plugin.del_plugin(index)
-    except BaseException:
-        pass
-    else:
         plugin_box.delete(0, tkinter.END)
         plugin_box.delete(0, tkinter.END)
         plugin_box.insert(0, *plugin_list)
         plugin_box.insert(0, *plugin_list)
+    finally:
+        pass
 
 
 
 
 def show_plugin():
 def show_plugin():
     index = plugin_box.curselection()[0]
     index = plugin_box.curselection()[0]
     try:
     try:
         code, name = plugin.show_plugin(index)
         code, name = plugin.show_plugin(index)
-    except BaseException:
-        pass
-    else:
         code_window(name)[0].insert(tkinter.END, code)
         code_window(name)[0].insert(tkinter.END, code)
+    finally:
+        pass
 
 
 
 
 def system_main():
 def system_main():

Algúns arquivos non se mostraron porque demasiados arquivos cambiaron neste cambio