androidpythonadbmonkeyrunner

How can I prevent new instances of background processes when calling adb in python subprocess module


PROBLEM: Every time I run this python function in my monkeyrunner.py script, it opens a new background instance of (cmd, adb, and conhost). And so, in my automation script, if I have a loop that uses that 100 times, I'm going to see 100 of each cmd, adb, and conhost running in the background (I know this because I enter "ps" in powershell to get the list of processes.) The purpose of the function, if you're curious, is to look for logcat messages from the USB attached Android tablet, to see when processes are finished, so that the script knows when to command screen touches to move forward with automation testing.

action = "____"
waitTime = 1
def adb(logMessage, action):
    start = time.time()
    p = subprocess.Popen("adb logcat -v time", shell=True, cwd="C:\Users\<USERNAME>\AppData\Local\Android\sdk\platform-tools", stdout=subprocess.PIPE)
    for line in p.stdout:
        if logMessage in line:
            print("Found message!")
            break
            pass
        else:
            continue

QUESTION: How can I use "subprocess" to open adb WITHOUT opening a new instance each time? Is there a way to close the subprocess in the same function?


Solution

  • I figured it out. To prevent a new session of adb from opening in the background per each time this function is called, all I had to do is place the "p" variable outside the function.... like this...

    p = subprocess.Popen("adb logcat -v time", shell=True, cwd="C:\Users\<USERNAME>\AppData\Local\Android\sdk\platform-tools", stdout=subprocess.PIPE)
    action = "____"
    waitTime = 1
    def adb(logMessage, action):
        start = time.time()
        for line in p.stdout:
            if logMessage in line:
                print("Found message!")
                break
                pass
            else:
                continue
    

    There is still the issue of a single adb session that opens and does not close after the script is run. So, now, instead of 180 sessions (or more) opening, there is a single one. If I find out how to close the session I will update this ticket.