使用MonkeyRunner时,经常会出现类似以下错误:

120830 18:39:32.755:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] Unable to get variable: display.density
120830 18:39:32.755:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice]java.net.SocketException: Connection reset

据我所读,有时adb连接会变坏,您需要重新连接。唯一的问题是,我无法捕获SocketException。我将这样包装代码:
try:
    density = self.device.getProperty('display.density')
except:
    print 'This will never print.'

但是,显然异常并未一直引发到调用者。我已经验证了MonkeyRunner/jython可以按照我期望的方式捕获Java异常:
>>> from java.io import FileInputStream
>>> def test_java_exceptions():
...     try:
...         FileInputStream('bad mojo')
...     except:
...         print 'Caught it!'
...
>>> test_java_exceptions()
Caught it!

我该如何处理这些套接字异常?

最佳答案

每次启动MonkeyRunner时,都会遇到该错误,因为脚本停止时设备上的monkey --port 12345命令不会停止。这是猴子的 bug 。

解决此问题的一种更好的方法是在将SIGINT发送到脚本时(当ctrl+c时)杀死猴子。换句话说:$ killall com.android.commands.monkey

快速的方法:

from sys, signal
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

device = None

def execute():
    device = MonkeyRunner.waitForConnection()
    # your code

def exitGracefully(self, signum, frame):
    signal.signal(signal.SIGINT, signal.getsignal(signal.SIGINT))
    device.shell('killall com.android.commands.monkey')
    sys.exit(1)

if __name__ == '__main__'
    signal.signal(signal.SIGINT, exitGracefully)
    execute()

编辑:
作为附录,我还找到了一种注意到Java错误的方法:Monkey Runner throwing socket exception broken pipe on touuch

关于jython - 如何在MonkeyRunner中捕获SocketException?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12208269/

10-09 06:57