处理线程内的无限循环函数

Handle infinite loop function inside a thread

我正在做一个 python 2.7 插件,可以在 android 设备上执行一些测试。

我的一个测试使用了 adb 命令,但此命令在某些设备上执行无限循环。

命令:adb shell am start -W -a android.intent.action.VOICE_COMMAND

预期输出:

Starting: Intent { act=android.intent.action.VOICE_COMMAND }
Status: ok
Activity: com.google.android.googlequicksearchbox/com.google.android.apps.gsa.velour.dynamichosts.TransparentVelvetDynamicHostActivity
ThisTime: 241
TotalTime: 659
WaitTime: 684
Complete

在我的大多数设备上,此命令运行良好,但在其他设备上,它会循环运行,并且永远不会 return 某些东西。

我试图将此命令调用到一个线程中,但即使这样做我也不知道如何在超时后终止该线程。

这是我已经尝试过的方法(参见 this),但是 none 这些方法有效,因为线程被锁定在无限循环调用中,所以我无法检查 "end" 变量被设置到这个线程中,也没有处理事件。

有没有办法在一定时间后用这样的东西杀死这个线程? =>

endtime = time.time() + 20
t1 = MyThread(my_func, "my_args", "my_args2")
while True:
    if time.time() > endtime:
        end_thread(t1) # or t1.end() or idk
    else:
        time.sleep(1)

解决了我的问题。

我使用了这样的子流程:

Module command.py

import subprocess
# [...]
def execute(cmd, args=None, display_cmd=False, disable_out=False, disable_error=False, no_wait=False, is_shell=False):
    if cmd is None:
        return None

    cmd_args = [cmd]

    if args is not None:
        for arg in args:
            cmd_args.append(str(arg))

    if display_cmd:
        str_cmd = None
        for arg in cmd_args:
            if str_cmd is None:
                str_cmd = str(arg)
            else:
                str_cmd = str_cmd + " " + str(arg)
        Logs.instance().debug(str_cmd)

    std_out = subprocess.PIPE
    if disable_out:
        std_out = DEVNULL

    if no_wait:
        subprocess.Popen(cmd_args, stdin=None, stdout=None, stderr=None, shell=is_shell)
        return None
    elif disable_error:
        p = subprocess.Popen(cmd_args, stdout=std_out, stderr=DEVNULL, shell=is_shell)
    else:
        p = subprocess.Popen(cmd_args, stdout=std_out, shell=is_shell)

    if disable_out:
        return None
    else:
        out = p.stdout.read()
        return out

Module adb.py

def shell(cmd, no_wait=False):
    data = cmd.split()
    if data[0] != "shell":
        data.insert(0, "shell")
    if no_wait:
        result = command.execute("adb", data, no_wait=True)
    else:
        result = command.execute("adb", data)
    return result

My plugin

def _my_test(self, x, y):
    result = adb.shell("shell am start -W -a android.intent.action.VOICE_COMMAND", no_wait=True)
    if not result:
        # handle
    else:
        # [...]

谢谢,希望有一天能对某人有所帮助