Skip to main content
 首页 » 编程设计

android之Python之stdout 的 Android logcat 输出到 textview 然后保存到 .txt 文件错误

2025年05月04日11pengyingh

我有以下 Python 代码,它通过 stdout 使用 Android logcat 将日志从手机中提取到 wxPython 文本字段中。 我登录到我的应用程序,用户名 jack 和密码 Jack@123$ logcat 输出因错误而停止,它似乎不喜欢 @ 或 $ 符号:

    return codecs.charmap_decode(input,errors,decoding_table) 
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 76: character maps to <undefined> 

或者当我尝试使用文本控件的 GetValue() 将其保存到打开以供写入的 .txt 文件中时:

UnicodeEncodeError: 'ascii' codec can't encode characters in position  204447-204449: ordinal not in range(128) 

logcat函数的代码如下

def logcat(self): 
   params = [toolsDir + "\\adb.exe", "logcat"] 
   p = Popen(params, stdout=subprocess.PIPE, bufsize=1) 
   for line in p.stdout: 
       #line = line.decode('Latin-1') 
       self.progressBox.AppendText(line) 
 
def saveLog(self,e): 
    f = open(outDir + '\\' + pkgName + '\\' + pkgName + '_logcat.txt', 'w') 
    f.write(self.progressBox.GetValue()) 
    f.close() 

使用标准输出对这些符号实现解码的正确方法是什么。 谢谢

请您参考如下方法:

编辑: 答案如下,我不得不从标准输出解码('utf-8')到文本框,然后在写入文件时编码('utf-8')。

    for line in p.stdout: 
        self.progressBox.AppendText(line.decode('utf-8')) 
 
 
    f.write(self.progressBox.GetValue().encode('utf-8'))