2017-07-30 69 views
1

我有一個使用subprocess.Popen啓動子進程的python腳本。子進程然後啓動一個外部命令(在我的情況下,它播放一個MP3)。 python腳本需要能夠中斷子進程,所以我使用了描述here的方法,該方法爲子進程提供了自己的會話ID。不幸的是,當我現在關閉python腳本時,子進程將繼續運行。Python,在腳本結束時使用不同的SID關閉子進程

如何確保從腳本啓動的子進程,但是如果在python腳本停止時仍然會關閉不同的會話ID?

回答

0

TL; DR更改POPEN PARAMS:拆分了POPEN CMD(前"list -l" - >["list", "-l"]),並使用Shell=False

~~~

迄今爲止所見過的最佳解決方案wa我只是不使用shell=True作爲Popen的一個參數,因爲我並不真的需要shell=True,所以我只是簡單地使用它,因爲Popen不會識別我的cmd字符串,而且我太懶惰也把它分成了一個參數列表。這給我帶來了很多其他問題(例如,使用.terminate()變成同時使用外殼變得更復雜了,需要有它的會話ID,見here

只需從一個字符串分割CMD成參數列表讓我使用Popen.terminate()而不必給它自己的會話ID,通過沒有一個單獨的會話ID進程將被關閉,當python腳本停止

0


Is there any way to kill a Thread in Python? ,並確保您使用它作爲線程

import threading 
from subprocess import call 
def thread_second(): 
    call(["python", "secondscript.py"]) 
processThread = threading.Thread(target=thread_second) # <- note extra ',' 
processThread.start() 

print 'the file is run in the background' 
+0

我正在調查這一點,我不知道它是儘管在我的情況下是一個很好的解決方案,因爲子進程是外部命令。從這篇文章中,python線程不太好處理中斷,因此不處理好關閉外部命令 – Alter

+0

閱讀此帖殺死線程 – 2017-07-30 21:17:41

+0

https://stackoverflow.com/questions/323972/is-there-any-way-to- kill-a-thread-in-python – 2017-07-30 21:17:52