5

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

我有一个用java编写的程序。它发送的每个并条框标签:“Fps:”消息:数字

我希望这条消息触发我可以在我的python脚本中捕获的事件,以便我可以绘制一个fps-meter。

4

2 回答 2

11

看看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_lineandupdate_fps函数。

于 2012-07-17T14:36:43.983 回答
6

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

$ adb logcat | python yourscript.py

现在,您可以从sys.stdin上的 logcat 读取并根据需要对其进行解析。

于 2012-07-17T14:28:15.383 回答