Search code examples
pythonpython-3.xsubprocesswaitpopen

How to force wait() to completely wait for subprocess? wait() can not work


I want to process the command1 by popen(python) and then run another command2 when the first one is finished. when I use wait() to make it work but it did not work.why? Does any one can help me?

def ant_debug():
    ant_debug_cmd = 'cmd /k ant debug'
    os.system(ant_debug_cmd)

def adb_install():
    apk_debug_path = walk_dir('.\\bin')
    adb_install_cmd = 'cmd /k adb install -r ' + apk_debug_path
    os.system(adb_install_cmd)

child = subprocess.call(ant_debug())
if child.wait() == 0:
    adb_install()

Solution

  • There are several problems with your code, and it is no suprise it doesn't run.

    You do not have to call .wait() when using subprocess.call(). That function takes care of the Process.wait() call for you.

    Instead, subprocess.call() returns the exit code directly. Quoting the subprocess.call() documentation:

    Run the command described by args. Wait for command to complete, then return the returncode attribute.

    Emphasis mine.

    Moreover, your ant_debug() function doesn't return anything (let alone a command to run). Instead it runs the ant command using os.system()! Remove that call all together. Use subprocess.call() instead of os.system().

    Rewriting your code to use just subprocess.call() would be:

    retcode = subprocess.call(['ant', 'debug'])
    
    if retcode == 0:
        apk_debug_path = walk_dir('.\\bin')
        adb_install_cmd = ['adb', 'install', '-r', apk_debug_path]
        subprocess.call(adb_install_cmd)
    

    where we pass in the command to run plus its arguments as a list of strings.

    I've removed the cmd /k prefix; just run ant directly; no shell is needed here. The /k switch even prevents the cmd shell from closing. The return value of cmd is not necessarily the same as what ant returned.