【发布时间】:2012-07-17 14:23:23
【问题描述】:
是否可以在 python 中读取通过 LogCat 发送的信息?
我有一个用 java 编写的程序。
每个并条机发送标签:“Fps:”消息:编号
我希望这条消息触发我可以在我的 python 脚本中捕获的事件,以便我可以绘制一个 fps-meter。
【问题讨论】:
标签: android python events logcat android-logcat
是否可以在 python 中读取通过 LogCat 发送的信息?
我有一个用 java 编写的程序。
每个并条机发送标签:“Fps:”消息:编号
我希望这条消息触发我可以在我的 python 脚本中捕获的事件,以便我可以绘制一个 fps-meter。
【问题讨论】:
标签: android python events logcat android-logcat
看看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_line 和 update_fps 函数。
【讨论】:
我会将adb logcat 重定向到您的python 脚本。这看起来像:
$ adb logcat | python yourscript.py
现在您可以从sys.stdin 上的 logcat 中读取数据,然后根据需要进行解析。
【讨论】: