2016-10-20 46 views
3

我有一個Python腳本,它使用subprocess.Popen()啓動另一個Python腳本的子進程。這個子進程使用Popen啓動另一個子進程(另一個Python腳本)。 腳本A調用腳本B調用腳本C. 如果我使用os.kill()終止進程腳本B,它會終止運行腳本C的進程。 如果沒有任何方法可以做到這一點。Python中的子進程終止

回答

2

現在,如果腳本A殺死B使用os.kill那麼C本身不會被殺死。

爲了確保這一點,腳本B可以照顧殺死C當它退出

# this is in script B 
import functools, atexit 

def kill_children(*pids): 
    import os, signal 

    for pid in pids or []: 
     os.kill(pid, signal.SIGTERM) 

# we start a process for C 
c_pid = ... 

# kill C when we we exit 
atexit.register(functools.partial(kill_children, c_pid)) 
+0

也許這將是一個想法,這裏使用'os.killpg',因爲它會殺死所有的孩子們。 –