Python subprocess: callback when cmd exits

后端 未结 7 1622
暗喜
暗喜 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 had same problem, and solved it using multiprocessing.Pool. There are two hacky tricks involved:

    1. make size of pool 1
    2. pass iterable arguments within an iterable of length 1

    result is one function executed with callback on completion

    def sub(arg):
        print arg             #prints [1,2,3,4,5]
        return "hello"
    
    def cb(arg):
        print arg             # prints "hello"
    
    pool = multiprocessing.Pool(1)
    rval = pool.map_async(sub,([[1,2,3,4,5]]),callback =cb)
    (do stuff) 
    pool.close()
    

    In my case, I wanted invocation to be non-blocking as well. Works beautifully

提交回复
热议问题