我正在使用 python 模块lxml
并psutil
记录一些系统指标以放置在 XML 文件中并复制到远程服务器以供 php 解析并显示给用户。
但是,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 文本?还是我这样做完全错了?
感谢您的任何帮助,您可以提供。