通过 Python 从 Android 访问 LogCat

Posted

技术标签:

【中文标题】通过 Python 从 Android 访问 LogCat【英文标题】:Accessing LogCat from Android via Python 【发布时间】:2012-07-17 14:23:23 【问题描述】:

是否可以在 python 中读取通过 LogCat 发送的信息?

我有一个用 java 编写的程序。 每个并条机发送标签:“Fps:”消息:编号 我希望这条消息触发我可以在我的 python 脚本中捕获的事件,以便我可以绘制一个 fps-meter。

【问题讨论】:

【参考方案1】:

看看subprocess。以下代码改编自Stefaan Lippens

import Queue
import subprocess
import threading


class AsynchronousFileReader(threading.Thread):
    '''
    Helper class to implement asynchronous reading of a file
    in a separate thread. Pushes read lines on a queue to
    be consumed in another thread.
    '''

    def __init__(self, fd, queue):
        assert isinstance(queue, Queue.Queue)
        assert callable(fd.readline)
        threading.Thread.__init__(self)
        self._fd = fd
        self._queue = queue

    def run(self):
        '''The body of the tread: read lines and put them on the queue.'''
        for line in iter(self._fd.readline, ''):
            self._queue.put(line)

    def eof(self):
        '''Check whether there is no more content to expect.'''
        return not self.is_alive() and self._queue.empty()


# You'll need to add any command line arguments here.
process = subprocess.Popen(["logcat"], stdout=subprocess.PIPE)

# Launch the asynchronous readers of the process' stdout.
stdout_queue = Queue.Queue()
stdout_reader = AsynchronousFileReader(process.stdout, stdout_queue)
stdout_reader.start()

# Check the queues if we received some output (until there is nothing more to get).
while not stdout_reader.eof():
    while not stdout_queue.empty():
        line = stdout_queue.get()
        if is_fps_line(line):
            update_fps(line)

当然,您需要自己编写 is_fps_lineupdate_fps 函数。

【讨论】:

酷,谢谢老兄! :D 正是我想要的:)))) 虽然 xD 给出了此错误但不起作用: Traceback (last recent call last): File "C:\Users\user\Desktop\Eclipse Workspace\ThirdWorkspace\test.pydev\src\FpsMeter.py" ,第 116 行,在 中 process = subprocess.Popen(["logcat"], stdout=subprocess.PIPE) 文件 "C:\Python27\lib\subprocess.py",第 679 行,在 init errread, errwrite) File "C:\Python27\lib\subprocess.py", line 896, in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified 标记的行包含以下代码:process = subprocess.Popen(["logcat"], stdout=subprocess.PIPE) 此代码假定 logcat 在您的路径上。如果它不在您的运行时路径上,那么您需要提供 logcat 的完整路径(例如“C:\Program Files\...\logcat”)来代替“logcat”字符串。 logcat 在 android 目录中不存在。您可以通过控制台中的“adb logcat”启动 android...事件提供完整路径 C:\Program Files (x86)\Android\android-sdk\platform-tools\logcat 它不起作用。【参考方案2】:

我会将adb logcat 重定向到您的python 脚本。这看起来像:

$ adb logcat | python yourscript.py

现在您可以从sys.stdin 上的 logcat 中读取数据,然后根据需要进行解析。

【讨论】:

以上是关于通过 Python 从 Android 访问 LogCat的主要内容,如果未能解决你的问题,请参考以下文章