Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def loadfile(self):
- """
- attempts to read files, w/ all errors that i care to implement
- """
- filepath_cfgfile = os.path.join(os.path.dirname(__file__), '') + "read_cfg"
- keys_read = []
- missingkeys = []
- missingkeys_no = 0
- linecount = 1 # DT
- with open(filepath_cfgfile, 'r') as open_cfgfile:
- """
- open safely, as always! ^^
- """
- for line in open_cfgfile:
- """
- for every line in the cfg-file --
- """
- line = line.strip().lower()
- # DT
- # if not line.startswith("#") and not line.startswith(" ") and not line.startswith("#\n"):
- # print "{0:>3} {1}".format(linecount, line)
- linecount += 1 # compare total lines read vs. key lines read
- errorstring = \
- """
- Something went wrong!
- Can't read line from read_cfg. Check syntax! Line below:
- ========================================================
- """+"\n"+line+"\n\n Continue anyway?"
- for key in self.arglist:
- """
- -- go through every keyword that should be interpreted &/ found --
- """
- if line.startswith(key.lower()):
- """ # enabled user mix up of uppercase letters in cfg variables..
- -- checks if the line starts with one of the keywords given --
- """
- keys_read += [key]
- try:
- """
- -- now interpret and set the value from that line, with its
- corresponding keyword in the dictionary!
- / remember:
- * key is a 'key' for dict containing
- the selection of parameter args.
- * obj becomes 'key' for the dict that determines
- what action to perform; the parameter arg's
- value of what to read.
- """
- obj = line[line.find("=")+1:].strip().lower()
- if obj.find(".") == -1:
- " No punctuations == . are in the line "
- pass
- else:
- print
- print "Reading line:"
- print line
- print
- print "Please do not use dots, punctuations, '.', in cfg file."
- sys.exit("\n\n Edit your cfg. Now exiting.")
- # uppercase is lowered to conform with self.actionkeys
- # DT
- # print "object being read:", obj
- # print "type of object:", type(obj)
- # print "need to find keyword in list:"
- # print " "*4, self.actionkeys
- if isinstance(obj, str) and \
- key == "what":
- """
- ---> interpret what to read!
- catches the keys' string names and compares with keywords;
- the first of above test should always be true, but...
- just being thorough.
- """
- # DT
- # print "got through the string test at key, object read:",\
- # key, ":", obj
- """
- First key: "what"
- ====================================
- | WHAT string assignment below |
- ====================================
- """
- if key in missingkeys:
- """
- * key is in missing keys list
- so as NOT to create duplicate the keys in list;
- ==> ignores current key for the line
- (some times i hate iterators)
- """
- # DT
- # print "passing"
- pass
- elif key not in missingkeys and \
- obj in self.actionkeys:
- """
- * key NOT missing (yet)
- * obj is recognized.
- checks if user's input is part of the
- keywords that may be used for determining
- dataset to read.
- ==> Success! text assigned to dict[key], WITH
- its correct interpretation!
- """
- self.read_params[key] = obj
- # DT
- # print "success; assigned:", self.read_params
- # print "to :", obj
- # elif isinstance(obj, str) and key == "what":
- # """
- # catches multiple tasks/datasets to perform/read
- # # --- can't be bothered right now
- # """
- elif key not in missingkeys and \
- obj not in self.actionkeys:
- """
- * key is NOT missing (yet)
- * obj is NOT recognized!
- - obj does not correspond to keyword
- so, basically, user has input something
- unrecognized!
- ==> add key to missing keys list
- ==> add one to counter of missing keys
- ==> add obj to dict[key] anyway, will fix this later,
- anyway!
- NOTE: if this actually happens; should ONLY happen ONCE
- considering the first if-test here.
- """
- # DT
- # print self.read_params[key]
- # print "key NOT missing, obj NOT recognized:"
- # print key, ":", obj
- missingkeys.append(key)
- missingkeys_no += 1
- self.read_params[key] = obj
- else:
- print "\n\n\n========================="
- print "I have to try and see how \
- this section would apply. Shutting down."
- sys.exit()
- # DT
- # print "\n\nkey != 'what'\n"
- """
- All keys except "what":
- ============================
- | TUPLES' values below |
- ============================
- """
- elif isinstance(eval(obj), tuple) and \
- key != "what" and \
- key not in self.toggles:
- """
- catches:
- * tuple values
- * items not expected to be strings for 'what'
- * non-self.toggles
- """
- # DT
- # print "\nInside tuple check! :D\n"
- if any(self.tuple_parameters) == False:
- " Create list with key, if list is empty. "
- self.tuple_parameters = [key]
- self.read_params[key] = eval(obj)
- elif any(self.tuple_parameters) == True and \
- key not in self.tuple_parameters:
- """
- # 1. checks if list is already created
- # 2. does not allow for duplicate keys to be made
- ==> Success! Tuple added!
- """
- self.tuple_parameters.append(key)
- self.read_params[key] = eval(obj)
- else:
- " Failure. Do better. "
- sys.exit("\n\n Tuple key error!\n\n Exiting\n\n")
- """
- ===========================
- | INTS' values below |
- ===========================
- """
- elif isinstance(eval(obj), int) and \
- key != "what" and \
- key not in self.toggles:
- """
- catches ints, non-self.toggles
- """
- self.read_params[key] = int(obj)
- elif isinstance(eval(obj), float) and \
- key != "what" and \
- key not in self.toggles:
- """
- catches ints given as floats, non-self.toggles
- """
- self.read_params[key] = int(obj)
- """
- ==============================
- | TOGGLES' values below |
- ==============================
- """
- elif isinstance(eval(obj), int) and \
- key != "what" and \
- key in self.toggles:
- """
- catches ints, in self.toggles
- """
- self.read_params[key] = int(obj)
- elif isinstance(eval(obj), float) and \
- key != "what" and \
- key in self.toggles:
- """
- catches ints given as floats, in self.toggles
- """
- self.read_params[key] = int(obj)
- else:
- """
- honestly, if you've configured the cfg in a way that you
- came to this point, then i have no idea what you're thinking
- """
- print "\n\n\n ### Impossible else!!!!!\n\n\n"
- if not self.errhand_userinput(errorstring):
- sys.exit("1 " + self.inigo)
- except:
- print "\n\n Exception in line's type recognition \n\n"
- if not self.errhand_userinput(errorstring):
- sys.exit("2 " + self.inigo)
- open_cfgfile.close()
- """
- these keys are now read
- """
- print "Total parameters loaded:", len(keys_read)
- print "Parameters initialized with values:"
- for key in keys_read:
- print "{:>10s} : {:>5s}".format(key, str(self.read_params[key]) )
- """
- in case user screws up some stuff in cfg, ask to load in some defaults
- """
- keys_not_read = list(set(self.read_params.keys()) - set(keys_read))
- missingkeys_no += len(keys_not_read) # is actually declared further up!
- print missingkeys
- if missingkeys_no >= 1:
- print "\nTotal no. of parameters not read =", missingkeys_no
- print "\nParameters not initialized:"
- for key in keys_not_read:
- print "{:>10s} : {:>5s}".format(key, str(self.read_params[key]))
- print "\nCan load default parameters for these, shown below:"
- for key in keys_not_read:
- print "{:>10s} : {:>5s}".format(key, str(self.default_vals[key]))
- if self.errhand_userinput("Continue with this/these values, or edit cfg properly first?"):
- print "\nParameters being set to:"
- for key in keys_not_read:
- self.read_params[key] = self.default_vals[key]
- print "{:>10s} : {:>5s}".format(key, str(self.self.read_params[key]))
- else:
- sys.exit("3 " + self.inigo)
- """
- self.read_params and its values should now be read.
- Now: Verify ranges & Set values globally
- """
- # DT
- # print "\n\ntuple_parameters ==", self.tuple_parameters, "\n\n"
- if any(self.tuple_parameters) == True:
- """
- multiple parameters' values - allows for both integers and tuples
- """
- for key in self.arglist[:6]:
- """
- multi's set-making values for:
- what indraN, iA, iB, subfolder, fftfile
- [ 0, 1, 2, 3, 4, 5]
- """
- # print self.arglist[:6]
- # note: possible sets of values have names accordingly:
- # (self.'keyname'_set)
- # # DT
- # print
- # print "multip - sets:"
- # print key, ":", self.read_params[key]
- # print self.read_params[key], "=", type(self.read_params[key])
- # if isinstance(self.read_params[key], tuple):
- # print "types{0} : ({1}, {2})".format( self.read_params[key], \
- # type(self.read_params[key][0]), type(self.read_params[key][1]) )
- # print "\n\nconsider:", key, ":", self.read_params[key]
- if key=="what":
- " This assigns string of task names "
- # DT
- # print "\n\nconsider:", key, ":", self.read_params[key]
- # exec("self.%s_set = 0" % key)
- # exec("print self.%s_set" % key)
- # exec(self.read_params[key])
- # exec("self.%s_set = %s" % (key, self.read_params[key] ) )
- print
- print key, self.read_params[key], type(key), type(self.read_params[key])
- print self.read_params
- sys.exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement