Python subprocess: callback when cmd exits

后端 未结 7 1633
暗喜
暗喜 2020-11-28 21:36

I\'m currently launching a programme using subprocess.Popen(cmd, shell=TRUE)

I\'m fairly new to Python, but it \'feels\' like there ought to be some api

7条回答
  •  生来不讨喜
    2020-11-28 22:27

    I modified Daniel G's answer to simply pass the subprocess.Popen args and kwargs as themselves instead of as a separate tuple/list, since I wanted to use keyword arguments with subprocess.Popen.

    In my case I had a method postExec() that I wanted to run after subprocess.Popen('exe', cwd=WORKING_DIR)

    With the code below, it simply becomes popenAndCall(postExec, 'exe', cwd=WORKING_DIR)

    import threading
    import subprocess
    
    def popenAndCall(onExit, *popenArgs, **popenKWArgs):
        """
        Runs a subprocess.Popen, and then calls the function onExit when the
        subprocess completes.
    
        Use it exactly the way you'd normally use subprocess.Popen, except include a
        callable to execute as the first argument. onExit is a callable object, and
        *popenArgs and **popenKWArgs are simply passed up to subprocess.Popen.
        """
        def runInThread(onExit, popenArgs, popenKWArgs):
            proc = subprocess.Popen(*popenArgs, **popenKWArgs)
            proc.wait()
            onExit()
            return
    
        thread = threading.Thread(target=runInThread,
                                  args=(onExit, popenArgs, popenKWArgs))
        thread.start()
    
        return thread # returns immediately after the thread starts
    

提交回复
热议问题