core/source/logic/lib.py

119 lines
2.7 KiB
Python
Raw Normal View History

2023-03-22 11:06:32 +01:00
def dict_merge(core_dict, mantle_dict, recursive = False):
result_dict = {}
for current_dict in [core_dict, mantle_dict]:
for (key, value, ) in current_dict.items():
if (not (key in result_dict)):
result_dict[key] = value
else:
if (recursive and (type(result_dict[key]) == dict) and (type(value) == dict)):
result_dict[key] = dict_merge(result_dict[key], value)
elif (recursive and (type(result_dict[key]) == list) and (type(value) == list)):
result_dict[key] = (result_dict[key] + value)
else:
result_dict[key] = value
return result_dict
2022-11-29 23:53:14 +01:00
def file_read(path):
handle = open(path, "r")
content = handle.read()
handle.close()
return content
2023-03-22 11:06:32 +01:00
def file_write(path, content, options = None):
options = dict_merge(
{
"append": False,
},
({} if (options is None) else options)
)
handle = open(path, "a" if options["append"] else "w")
2022-11-29 23:53:14 +01:00
handle.write(content)
handle.close()
def string_coin(template, arguments):
result = template
for (key, value, ) in arguments.items():
result = result.replace("{{%s}}" % key, value)
return result
def get_current_timestamp():
return int(round(_time.time(), 0))
def env_get_language():
2022-12-05 08:16:29 +01:00
try:
env_lang = _os.environ.get("LANG")
locale = env_lang.split(".")[0]
language = locale.split("_")[0]
return language
except Exception as error:
return None
2022-11-29 23:53:14 +01:00
2023-03-03 14:13:08 +01:00
def shell_command(command):
result = _subprocess.run(
command,
2023-03-04 15:21:44 +01:00
capture_output = True,
shell = True,
2023-03-03 14:13:08 +01:00
)
return {
"return_code": result.returncode,
"stdout": result.stdout.decode(),
"stderr": result.stderr.decode(),
}
2023-03-04 15:10:08 +01:00
def format_bytes(bytes_):
units = [
{"label": "B", "digits": 0},
{"label": "KB", "digits": 1},
{"label": "MB", "digits": 1},
{"label": "GB", "digits": 1},
{"label": "TB", "digits": 1},
{"label": "PB", "digits": 1},
]
number = bytes_
index = 0
while ((number >= 1000) and (index < (len(units) - 1))):
number /= 1000
index += 1
return (
("%." + ("%u" % units[index]["digits"]) + "f %s")
% (
number,
units[index]["label"],
)
)
def sqlite_query_set(database_path, template, arguments):
connection = _sqlite3.connect(database_path)
cursor = connection.cursor()
result = cursor.execute(template, arguments)
connection.commit()
connection.close()
return result
def sqlite_query_put(database_path, template, arguments):
connection = _sqlite3.connect(database_path)
cursor = connection.cursor()
result = cursor.execute(template, arguments)
connection.commit()
connection.close()
return result
def sqlite_query_get(database_path, template, arguments):
connection = _sqlite3.connect(database_path)
cursor = connection.cursor()
result = cursor.execute(template, arguments)
rows = result.fetchall()
connection.close()
return rows