Ad

Handle Infinite Loop Function Inside A Thread

- 1 answer

I'm doing a python 2.7 plugin that perform some tests on android devices.

One of my test use an adb command, but this command is doing an infinite loop on some devices.

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

expected output:

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

On most of my devices this command work well but on other it loop and never return something.

I tryed to call this command into a thread, but even doing this I can't figure out how to kill that thread after a timeout.

Here is what I have already tryed (see this) but none of these work because the thread is locked into that infinite loop call and so I can't check if an "end" variable is set into this thread, nor handle event.

Is there a way to kill this Thread after a certain amount of time with something like this ? =>

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)
Ad

Answer

Resolved my issue.

I used subprocess like this:

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:
        # [...]

Thank you, hope it will help someone one day

Ad
source: stackoverflow.com
Ad