2016-09-16 24 views
0

我使用python模塊lxmlpsutil來記錄一些系統指標,將其放置在一個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文本?還是我這樣做完全錯了?

感謝您提供的任何幫助。

回答

2

text字段預計爲unicode或str,而不是任何其他類型(boot_timefloatlen()是int)。 所以只是轉換爲字符串非字符串兼容的元素:

# First system/hostname, so we know what machine this is 
etree.SubElement(child1, "name").text = socket.gethostname() # nothing to do 

# Then boot time, to get the time the system was booted. 
etree.SubElement(child1, "boottime").text = str(psutil.boot_time()) 

# and process count, see how many processes are running. 
etree.SubElement(child1, "proccount").text = str(len(psutil.pids())) 

結果:

b'<metrics>\n <basic>\n <name>JOTD64</name>\n <boottime>1473903558.0</boottime>\n <proccount>121</proccount>\n </basic>\n</metrics>\n' 

我認爲圖書館可以做isinstance(str,x)測試或str轉換,但它不是這樣設計的(如果你想用前導零顯示你的浮點數,截斷小數......)。 如果lib假定所有內容都是str,則它運行速度更快,這是大部分時間。

+0

那麼....我是在糾正這種情況。謝謝你回答我的無能!你的餅乾先生。 – Jguy

相關問題