[LABI] tema04 xml reader added

This commit is contained in:
TiagoRG 2023-04-03 21:01:30 +01:00
parent 7eea3c7abb
commit 3f050960f3
4 changed files with 68 additions and 0 deletions

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8" ?>
<conf>
<interval>1</interval>
<output>
<csv active="true" separator="," />
<xml active="false" />
</output>
<monitor>
<cpu active="true" />
<network active="true" />
<ram active="false" />
</monitor>
</conf>

View File

@ -0,0 +1,7 @@
time,cpu,ram,network
1679769801.7018511,20.0,,38943828
1679769802.702516,28.0,,38946821
1679769803.7031012,7.4,,38948575
1679769804.7034643,11.8,,38949179
1679769805.7041101,8.0,,38951189
1679769806.704759,7.1,,38951668
1 time cpu ram network
2 1679769801.7018511 20.0 38943828
3 1679769802.702516 28.0 38946821
4 1679769803.7031012 7.4 38948575
5 1679769804.7034643 11.8 38949179
6 1679769805.7041101 8.0 38951189
7 1679769806.704759 7.1 38951668

View File

@ -0,0 +1,30 @@
import csv
import time
import psutil
from lxml import etree
def main(args=None):
xml = etree.parse('../datafiles/conf.xml')
root = xml.getroot()
delimiter = root.findall("./output/csv")[0].attrib["separator"]
monitor_cpu = root.findall("./monitor/cpu")[0].attrib["active"]
monitor_ram = root.findall("./monitor/ram")[0].attrib["active"]
monitor_network = root.findall("./monitor/network")[0].attrib["active"]
with open("../datafiles/monitor.csv", "w") as f:
writer = csv.DictWriter(f, delimiter=delimiter, fieldnames=["time", "cpu", "ram", "network"])
writer.writeheader()
while True:
cpu = psutil.cpu_percent() if monitor_cpu == "true" else ""
ram = psutil.virtual_memory().percent if monitor_ram == "true" else ""
network = psutil.net_io_counters().bytes_sent if monitor_network == "true" else ""
writer.writerow({"time": time.time(), "cpu": cpu, "ram": ram, "network": network})
time.sleep(1)
if __name__ == '__main__':
main()

View File

@ -0,0 +1,18 @@
from lxml import etree
def main(args=None):
xml = etree.parse('../datafiles/conf.xml')
root = xml.getroot()
print(root.tag)
print_childs(root)
def print_childs(root):
for child in root:
print(child.tag, child.attrib, child.text)
print_childs(child)
if __name__ == '__main__':
main()