Advertisement
Guest User

Untitled

a guest
Aug 16th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 15.25 KB | None | 0 0
  1. def loadfile(self):
  2.     """
  3.    attempts to read files, w/ all errors that i care to implement
  4.    """
  5.     filepath_cfgfile = os.path.join(os.path.dirname(__file__), '') + "read_cfg"
  6.     keys_read       = []
  7.     missingkeys     = []
  8.     missingkeys_no  =  0
  9.    
  10.     linecount = 1 # DT
  11.  
  12.     with open(filepath_cfgfile, 'r') as open_cfgfile:
  13.         """
  14.        open safely, as always! ^^
  15.        """
  16.         for line in open_cfgfile:
  17.             """
  18.            for every line in the cfg-file --
  19.            """
  20.             line = line.strip().lower()
  21.            
  22.             # DT
  23.             # if not line.startswith("#") and not line.startswith(" ") and not line.startswith("#\n"):
  24.             #     print "{0:>3} {1}".format(linecount, line)
  25.             linecount += 1 # compare total lines read vs. key lines read
  26.            
  27.             errorstring = \
  28.             """
  29.            Something went wrong!
  30.            Can't read line from read_cfg. Check syntax! Line below:
  31.            ========================================================
  32.            """+"\n"+line+"\n\n Continue anyway?"
  33.  
  34.             for key in self.arglist:
  35.                 """
  36.                -- go through every keyword that should be interpreted &/ found --
  37.                """
  38.  
  39.                 if line.startswith(key.lower()):
  40.                     """ # enabled user mix up of uppercase letters in cfg variables..
  41.                    -- checks if the line starts with one of the keywords given --
  42.                    """
  43.                     keys_read += [key]
  44.                    
  45.                     try:
  46.                         """
  47.                        -- now interpret and set the value from that line, with its
  48.                        corresponding keyword in the dictionary!
  49.                          / remember:
  50.                            * key is a 'key' for dict containing
  51.                               the selection of parameter args.
  52.                            * obj becomes 'key' for the dict that determines
  53.                               what action to perform; the parameter arg's
  54.                               value of what to read.
  55.                        """
  56.                        
  57.                         obj = line[line.find("=")+1:].strip().lower()
  58.                        
  59.                         if obj.find(".") == -1:
  60.                             " No punctuations == . are in the line "
  61.                             pass
  62.  
  63.                         else:
  64.                             print
  65.                             print "Reading line:"
  66.                             print line
  67.                             print
  68.                             print "Please do not use dots, punctuations, '.', in cfg file."
  69.                             sys.exit("\n\n Edit your cfg. Now exiting.")
  70.                                 # uppercase is lowered to conform with self.actionkeys
  71.  
  72.                         # DT
  73.                         # print "object being read:", obj
  74.                         # print "type of object:", type(obj)
  75.                         # print "need to find keyword in list:"
  76.                         # print " "*4, self.actionkeys
  77.  
  78.  
  79.                         if isinstance(obj, str) and \
  80.                             key == "what":
  81.                             """
  82.                            ---> interpret what to read!
  83.                            catches the keys' string names and compares with keywords;
  84.                            the first of above test should always be true, but...
  85.                            just being thorough.
  86.                            """
  87.  
  88.                             # DT
  89.                             # print "got through the string test at key, object read:",\
  90.                             #         key, ":", obj
  91.  
  92.                             """
  93.                            First key: "what"
  94.                            ====================================
  95.                            |   WHAT string assignment below   |
  96.                            ====================================
  97.                            """
  98.                             if key in missingkeys:
  99.                                 """
  100.                                * key is in missing keys list
  101.                                so as NOT to create duplicate the keys in list;
  102.                                ==> ignores current key for the line
  103.                                        (some times i hate iterators)
  104.                                """
  105.  
  106.                                 # DT
  107.                                 # print "passing"
  108.  
  109.                                 pass
  110.  
  111.                             elif key not in missingkeys and \
  112.                                 obj in self.actionkeys:
  113.                                 """
  114.                                * key NOT missing (yet)
  115.                                * obj is recognized.
  116.                                checks if user's input is part of the
  117.                                keywords that may be used for determining
  118.                                dataset to read.
  119.                                ==> Success! text assigned to dict[key], WITH
  120.                                      its correct interpretation!
  121.                                """
  122.                                 self.read_params[key] = obj
  123.  
  124.                                 # DT
  125.                                 # print "success; assigned:", self.read_params
  126.                                 # print "to               :", obj
  127.  
  128.                                 # elif isinstance(obj, str) and key == "what":
  129.                                     # """
  130.                                     # catches multiple tasks/datasets to perform/read
  131.                                     # # --- can't be bothered right now
  132.                                     # """
  133.  
  134.                             elif key not in missingkeys and \
  135.                                 obj not in self.actionkeys:
  136.                                 """
  137.                                * key is NOT missing (yet)
  138.                                * obj is NOT recognized!
  139.                                  - obj does not correspond to keyword
  140.                                so, basically, user has input something
  141.                                    unrecognized!
  142.                                ==> add key to missing keys list
  143.                                ==> add one to counter of missing keys
  144.                                ==> add obj to dict[key] anyway, will fix this later,
  145.                                      anyway!
  146.                                NOTE: if this actually happens; should ONLY happen ONCE
  147.                                        considering the first if-test here.
  148.                                """
  149.                                 # DT
  150.                                 # print self.read_params[key]
  151.                                 # print "key NOT missing, obj NOT recognized:"
  152.                                 # print key, ":", obj
  153.  
  154.                                 missingkeys.append(key)
  155.                                 missingkeys_no        += 1
  156.                                 self.read_params[key]  = obj
  157.  
  158.                             else:
  159.                                 print "\n\n\n========================="
  160.                                 print "I have to try and see how \
  161.                                this section would apply. Shutting down."
  162.                                 sys.exit()
  163.  
  164.                             # DT
  165.                             # print "\n\nkey != 'what'\n"
  166.  
  167.  
  168.                             """
  169.                        All keys except "what":
  170.                        ============================
  171.                        |   TUPLES' values below   |
  172.                        ============================
  173.                            """
  174.                         elif isinstance(eval(obj), tuple)   and \
  175.                             key != "what"                   and \
  176.                             key not in self.toggles:
  177.                             """
  178.                            catches:
  179.                            * tuple values
  180.                            * items not expected to be strings for 'what'
  181.                            * non-self.toggles
  182.                            """
  183.                             # DT
  184.                             # print "\nInside tuple check! :D\n"
  185.  
  186.                             if any(self.tuple_parameters) == False:
  187.                                 " Create list with key, if list is empty. "
  188.                                 self.tuple_parameters = [key]
  189.                                 self.read_params[key] = eval(obj)
  190.  
  191.                             elif any(self.tuple_parameters) == True and \
  192.                                 key not in self.tuple_parameters:
  193.                                 """
  194.                                # 1. checks if list is already created
  195.                                # 2. does not allow for duplicate keys to be made
  196.                                ==> Success! Tuple added!
  197.                                """
  198.                                 self.tuple_parameters.append(key)
  199.                                 self.read_params[key] = eval(obj)
  200.  
  201.                             else:
  202.                                 " Failure. Do better. "
  203.                                 sys.exit("\n\n Tuple key error!\n\n Exiting\n\n")
  204.  
  205.  
  206.  
  207.                             """
  208.                        ===========================
  209.                        |   INTS' values below    |
  210.                        ===========================
  211.                            """
  212.                         elif isinstance(eval(obj), int) and \
  213.                             key != "what"               and \
  214.                             key not in self.toggles:
  215.                             """
  216.                            catches ints, non-self.toggles
  217.                            """
  218.                             self.read_params[key] = int(obj)
  219.  
  220.  
  221.                         elif isinstance(eval(obj), float)   and \
  222.                             key != "what"                   and \
  223.                             key not in self.toggles:
  224.                             """
  225.                            catches ints given as floats, non-self.toggles
  226.                            """
  227.                             self.read_params[key] = int(obj)
  228.  
  229.  
  230.  
  231.                             """
  232.                        ==============================
  233.                        |   TOGGLES' values below    |
  234.                        ==============================
  235.                            """
  236.                         elif isinstance(eval(obj), int)     and \
  237.                             key != "what"                   and \
  238.                             key in self.toggles:
  239.                             """
  240.                            catches ints, in self.toggles
  241.                            """
  242.                             self.read_params[key] = int(obj)
  243.  
  244.                         elif isinstance(eval(obj), float)   and \
  245.                             key != "what"                   and \
  246.                             key in self.toggles:
  247.                             """
  248.                            catches ints given as floats, in self.toggles
  249.                            """
  250.                             self.read_params[key] = int(obj)
  251.                        
  252.  
  253.                         else:
  254.                             """
  255.                            honestly, if you've configured the cfg in a way that you
  256.                            came to this point, then i have no idea what you're thinking
  257.                            """
  258.                             print "\n\n\n         ### Impossible else!!!!!\n\n\n"
  259.                             if not self.errhand_userinput(errorstring):
  260.                                 sys.exit("1 " + self.inigo)
  261.  
  262.  
  263.                     except:
  264.                         print "\n\n       Exception in line's type recognition   \n\n"
  265.                         if not self.errhand_userinput(errorstring):
  266.                             sys.exit("2 " + self.inigo)
  267.  
  268.         open_cfgfile.close()
  269.  
  270.  
  271.     """
  272.    these keys are now read
  273.    """
  274.     print "Total parameters loaded:", len(keys_read)
  275.     print "Parameters initialized with values:"
  276.     for key in keys_read:
  277.         print "{:>10s} : {:>5s}".format(key, str(self.read_params[key]) )
  278.  
  279.     """
  280.    in case user screws up some stuff in cfg, ask to load in some defaults
  281.    """
  282.     keys_not_read = list(set(self.read_params.keys()) - set(keys_read))
  283.     missingkeys_no += len(keys_not_read) # is actually declared further up!
  284.     print missingkeys        
  285.    
  286.     if missingkeys_no >= 1:    
  287.         print "\nTotal no. of parameters not read =", missingkeys_no
  288.         print "\nParameters not initialized:"
  289.         for key in keys_not_read:
  290.             print "{:>10s} : {:>5s}".format(key, str(self.read_params[key]))
  291.  
  292.         print "\nCan load default parameters for these, shown below:"
  293.        
  294.         for key in keys_not_read:
  295.             print "{:>10s} : {:>5s}".format(key, str(self.default_vals[key]))
  296.         if self.errhand_userinput("Continue with this/these values, or edit cfg properly first?"):
  297.             print "\nParameters being set to:"
  298.             for key in keys_not_read:
  299.                 self.read_params[key] = self.default_vals[key]
  300.                 print "{:>10s} : {:>5s}".format(key, str(self.self.read_params[key]))
  301.         else:
  302.             sys.exit("3 " + self.inigo)
  303.  
  304.  
  305.     """
  306.    self.read_params and its values should now be read.
  307.    Now: Verify ranges & Set values globally
  308.    """
  309.     # DT
  310.     # print "\n\ntuple_parameters ==", self.tuple_parameters, "\n\n"
  311.  
  312.  
  313.     if any(self.tuple_parameters) == True:
  314.         """
  315.        multiple parameters' values - allows for both integers and tuples
  316.        """
  317.         for key in self.arglist[:6]:
  318.             """
  319.            multi's set-making values for:
  320.            what indraN, iA, iB, subfolder, fftfile
  321.            [  0,     1,  2,  3,         4,       5]
  322.            """
  323.             # print self.arglist[:6]
  324.             # note: possible sets of values have names accordingly:
  325.             # (self.'keyname'_set)
  326.  
  327.             # # DT
  328.             # print
  329.             # print "multip - sets:"
  330.             # print key, ":", self.read_params[key]
  331.             # print self.read_params[key], "=", type(self.read_params[key])
  332.             # if isinstance(self.read_params[key], tuple):
  333.             #     print "types{0} : ({1}, {2})".format(   self.read_params[key], \
  334.             #         type(self.read_params[key][0]), type(self.read_params[key][1])  )
  335.            
  336.             # print "\n\nconsider:", key, ":", self.read_params[key]
  337.            
  338.            
  339.             if key=="what":
  340.                 " This assigns string of task names "
  341.                 # DT
  342.                 # print "\n\nconsider:", key, ":", self.read_params[key]
  343.  
  344.                 # exec("self.%s_set = 0" % key)
  345.                 # exec("print self.%s_set" % key)
  346.                 # exec(self.read_params[key])
  347.                 # exec("self.%s_set = %s"   % (key, self.read_params[key] ) )
  348.                
  349.                 print
  350.                 print key, self.read_params[key], type(key), type(self.read_params[key])
  351.                 print self.read_params
  352.                 sys.exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement