0
我使用python模塊lxml
和psutil
來記錄一些系統指標,將其放置在一個XML文件中,並複製到一個遠程服務器以供php解析並顯示給用戶。Python使用lxml寫入一個帶有系統性能數據的xml文件
但是,lxml在向XML的各個部分推送一些變量,對象等時給我帶來一些麻煩。
例如:
import psutil, os, time, sys, platform
from lxml import etree
# This creates <metrics>
root = etree.Element('metrics')
# and <basic>, to display basic information about the server
child1 = etree.SubElement(root, 'basic')
# First system/hostname, so we know what machine this is
etree.SubElement(child1, "name").text = socket.gethostname()
# Then boot time, to get the time the system was booted.
etree.SubElement(child1, "boottime").text = psutil.boot_time()
# and process count, see how many processes are running.
etree.SubElement(child1, "proccount").text = len(psutil.pids())
線來獲得系統主機名的作品。
然而接下來的兩行獲得啓動時間和進程計數誤差出來,用:
>>> etree.SubElement(child1, "boottime").text = psutil.boot_time()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "lxml.etree.pyx", line 921, in lxml.etree._Element.text.__set__ (src/lxml/lxml.etree.c:41344)
File "apihelpers.pxi", line 660, in lxml.etree._setNodeText (src/lxml/lxml.etree.c:18894)
File "apihelpers.pxi", line 1333, in lxml.etree._utf8 (src/lxml/lxml.etree.c:24601)
TypeError: Argument must be bytes or unicode, got 'float'
>>> etree.SubElement(child1, "proccount").text = len(psutil.pids())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "lxml.etree.pyx", line 921, in lxml.etree._Element.text.__set__ (src/lxml/lxml.etree.c:41344)
File "apihelpers.pxi", line 660, in lxml.etree._setNodeText (src/lxml/lxml.etree.c:18894)
File "apihelpers.pxi", line 1333, in lxml.etree._utf8 (src/lxml/lxml.etree.c:24601)
TypeError: Argument must be bytes or unicode, got 'int'
所以,這裏是我的XML的樣子,印刷:
>>> print(etree.tostring(root, pretty_print=True))
<metrics>
<basic>
<name>mercury</name>
<boottime/>
<proccount/>
</basic>
</metrics>
那麼,有沒有無論如何推動像我需要的浮動和整數到XML文本?還是我這樣做完全錯了?
感謝您提供的任何幫助。
那麼....我是在糾正這種情況。謝謝你回答我的無能!你的餅乾先生。 – Jguy