2016-09-16 39 views
0

私はPythonモジュールlxmlpsutilを使用して、XMLファイルに配置されるいくつかのシステムメトリックを記録し、PHPによって解析され、ユーザー。lxmlを使用してxmlファイルをシステムパフォーマンスデータで書き込むPython

しかし、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()) 

ラインシステムのホスト名の作品を取得します。

しかし次の2行で、ブート時間とプロセス数のエラーを出すために:だから

>>> 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> 

ので、そこにありますとにかく私は必要なように浮動小数点数とintをXMLテキストにプッシュするには?あるいは私はこれを完全に間違っているのですか?

ご協力いただきありがとうございます。

答えて

2

textフィールドは、他のタイプではなく、ユニコードまたは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())) 

結果:

私は図書館が isinstance(str,x)テストまたは str変換を行うことができたと
b'<metrics>\n <basic>\n <name>JOTD64</name>\n <boottime>1473903558.0</boottime>\n <proccount>121</proccount>\n </basic>\n</metrics>\n' 

、それはそのように設計されていませんでした(先行ゼロ、切り捨て小数点付き浮動小数点数を表示する場合はどうなりますか?)。 libがすべてがstrであると仮定すると、それはより速く動作します。ほとんどの時間です。

+0

まあ...私は状況を考えすぎた。私の無能さに感謝してくれてありがとう!あなたのためにクッキー。 – Jguy

関連する問題