kbc_toml.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import tomlkit
  2. # ----- Toml Methods -----
  3. def GetTomlDoc(tomlName:str):
  4. try:
  5. with open(tomlName, "rb") as t:
  6. doc = tomlkit.load(t)
  7. if doc == {}:
  8. input("error 0: could not found correct config file")
  9. exit()
  10. return doc
  11. except FileNotFoundError:
  12. input("error 0: could not found correct config file")
  13. # sec_respond?
  14. exit()
  15. def MatchTomlKey(tomlName:str, key:str, table:str="none") -> str:
  16. doc = GetTomlDoc(tomlName)
  17. if table == "none":
  18. return str(doc.item(key))
  19. elif table != "none":
  20. d = doc.unwrap()
  21. return str(d[table][key])
  22. # no differernt between ↑ MatchTomlKey() ↑ except receives and returns in list
  23. def MatchTomlKeys(tomlName:str, keys:list, table:str="none") -> list:
  24. doc = GetTomlDoc(tomlName)
  25. if table == "none":
  26. # rl == 'r'eturn 'l'ist
  27. rl = []
  28. for key in keys:
  29. try:
  30. rl.append(doc.item(key))
  31. except:
  32. pass
  33. return rl
  34. elif table != "none":
  35. rl = []
  36. d = doc.unwrap()
  37. for key in keys:
  38. try:
  39. rl.append(d[table][key])
  40. except:
  41. pass
  42. return rl
  43. def MatchTomlTable(tomlName:str, tableName:str, returnType:str="list"):
  44. d = GetTomlDoc(tomlName).unwrap()
  45. if returnType == "list":
  46. return list(d.get(tableName).values())
  47. elif returnType == "dict":
  48. return d