Python,脚本结束时使用不同的SID关闭子进程

时间:2017-07-30 20:40:57

标签: python linux subprocess python-multithreading

我有一个使用subprocess.Popen启动子进程的python脚本。然后子进程启动一个外部命令(在我的例子中,它播放一个mp3)。 python脚本需要能够中断子进程,因此我使用了here描述的方法,它为子进程提供了自己的会话ID。不幸的是,当我现在关闭python脚本时,子进程将继续运行。

如何确保从脚本启动子进程,但是当python脚本停止时,给定不同的会话ID仍会关闭?

2 个答案:

答案 0 :(得分: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'

答案 1 :(得分:0)

TL; DR 更改Popen参数:拆分Popen cmd(例如"list -l" - &gt; ["list", "-l"])并使用Shell=False

~~~

到目前为止我见过的最好的解决办法就是不要用shell=True作为Popen的论据,这很有效,因为我不需要shell=True,我只是因为Popen而使用它我不会识别我的cmd字符串而且我太懒了将它分成args列表。这导致了很多其他问题(例如使用.terminate()变得更加复杂,同时使用shell并且需要拥有其会话ID,请参阅here

简单地将cmd从字符串拆分为args列表让我使用Popen.terminate()而不必为其提供自己的会话ID,因为没有单独的会话ID,当python脚本为时,进程将被关闭停止