簡體   English   中英

AWS Lambda Python函數刪除尾隨的Unicode

[英]AWS Lambda Python function remove trailing unicode

我正在嘗試使用Python 3.6 AWS Lambda函數來解析從Cloudwatch發送的Windows日志。

這些以JSON的形式到達Lambda,因此我使用以下方法提取想要的字段:

for i in data['logEvents']
   message = json.dumps((i['message']))

這使我在我的message字符串:

"<Event xmlns='http://schemas.microsoft.com/win/2004/08/events/event'><System><Provider Name='Lfsvc'/><EventID Qualifiers='0'>2</EventID><Level>4</Level><Task>0</Task><Keywords>0x80000000000000</Keywords><TimeCreated SystemTime='2018-04-03T15:33:57.186213000Z'/><EventRecordID>25371</EventRecordID><Channel>System</Channel><Computer>EC2AMAZ-1KJC0H1</Computer><Security/></System><EventData></EventData><RenderingInfo Culture='en-US'><Message>Geolocation positioning has been disabled by the user.</Message><Level>Information</Level><Task></Task><Opcode>Info</Opcode><Channel></Channel><Provider></Provider><Keywords><Keyword>Classic</Keyword></Keywords></RenderingInfo></Event>\u0000"

然后,我嘗試將此字符串轉換為XML以與xmltodict或xml.etree.ElementTree一起使用,但是由於結尾處\ ,這兩個都返回格式錯誤的XML錯誤。

因此,我然后運行此命令以刪除unicode:

xml = re.sub(u'(\u0000)', "", message)

可以在本地python控制台上的計算機上正常工作,然后xmltodict和xml.etree.ElementTree都可以使用新創建的xml字符串。

但是,當我在Lambda函數中運行re.sub命令時, \仍保留在字符串的末尾。

我缺少明顯的東西嗎?

添加print(i['message'])的完整輸出

<Event xmlns='http://schemas.microsoft.com/win/2004/08/events/event'><System><Provider Name='Service Control Manager' Guid='{555908d1-a6d7-4695-8e1e-26931d2012f4}' EventSourceName='Service Control Manager'/><EventID Qualifiers='16384'>7036</EventID><Version>0</Version><Level>4</Level><Task>0</Task><Opcode>0</Opcode><Keywords>0x8080000000000000</Keywords><TimeCreated SystemTime='2018-04-03T15:31:31.854941100Z'/><EventRecordID>25365</EventRecordID><Correlation/><Execution ProcessID='712' ThreadID='4768'/><Channel>System</Channel><Computer>EC2AMAZ-1KJC0H1</Computer><Security/></System><EventData><Data Name='param1'>Volume Shadow Copy</Data><Data Name='param2'>running</Data><Binary>5600530053002F0034000000</Binary></EventData><RenderingInfo Culture='en-US'><Message>The Volume Shadow Copy service entered the running state.</Message><Level>Information</Level><Task></Task><Opcode></Opcode><Channel></Channel><Provider>Microsoft-Windows-Service Control Manager</Provider><Keywords><Keyword>Classic</Keyword></Keywords></RenderingInfo></Event>\u0000

非常感謝,戴夫

您的問題可能是由於在執行re.sub之前在消息字符串上使用json.dumps引起的。 請參見下面的示例:

import re, json

msg = "</Keywords></RenderingInfo></Event>\u0000"
xml_1 = re.sub(u'(\u0000)', "", msg)
print(xml_1)

message = json.dumps(msg)
xml_2 = re.sub(u'(\u0000)', "", message)
print(xml_2)

輸出量

</Keywords></RenderingInfo></Event>
"</Keywords></RenderingInfo></Event>\u0000"

如您在輸出中所看到的,似乎json.dumps在消息中引入了雙引號 ,這導致您的re.sub問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM