Python,当脚本结束时关闭具有不同 SID 的子进程
Python, close subprocess with different SID when script ends
我有一个 python 脚本,它使用 subprocess.Popen
启动子进程。然后子进程启动一个外部命令(在我的例子中,它播放 mp3)。 python 脚本需要能够中断子进程,因此我使用了 here 中描述的方法,它为子进程提供了自己的会话 ID。不幸的是,当我现在关闭 python 脚本时,子进程将继续 运行。
如何确保子进程从脚本启动,但在 python 脚本停止时给定不同的会话 ID 仍然关闭?
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'
TL;DR 更改 Popen 参数:拆分 Popen cmd(例如 "list -l"
-> ["list", "-l"]
)并使用 Shell=False
~~~
目前为止我看到的最好的解决方案就是不使用 shell=True
作为 Popen 的参数,这很有效,因为我并不真的需要 shell=True
,我只是在使用它因为 Popen 无法识别我的 cmd 字符串,而且我太懒了,所以将它拆分成一个 args 列表。这给我带来了很多其他问题(例如,使用 .terminate()
变得更加复杂,而使用 shell 并且需要有它的会话 ID,参见 here)
只需将 cmd 从字符串拆分为 args 列表,我就可以使用 Popen.terminate() 而无需为其提供自己的会话 ID,因为没有单独的会话 ID,进程将在以下时间关闭python 脚本已停止
我有一个 python 脚本,它使用 subprocess.Popen
启动子进程。然后子进程启动一个外部命令(在我的例子中,它播放 mp3)。 python 脚本需要能够中断子进程,因此我使用了 here 中描述的方法,它为子进程提供了自己的会话 ID。不幸的是,当我现在关闭 python 脚本时,子进程将继续 运行。
如何确保子进程从脚本启动,但在 python 脚本停止时给定不同的会话 ID 仍然关闭?
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'
TL;DR 更改 Popen 参数:拆分 Popen cmd(例如 "list -l"
-> ["list", "-l"]
)并使用 Shell=False
~~~
目前为止我看到的最好的解决方案就是不使用 shell=True
作为 Popen 的参数,这很有效,因为我并不真的需要 shell=True
,我只是在使用它因为 Popen 无法识别我的 cmd 字符串,而且我太懒了,所以将它拆分成一个 args 列表。这给我带来了很多其他问题(例如,使用 .terminate()
变得更加复杂,而使用 shell 并且需要有它的会话 ID,参见 here)
只需将 cmd 从字符串拆分为 args 列表,我就可以使用 Popen.terminate() 而无需为其提供自己的会话 ID,因为没有单独的会话 ID,进程将在以下时间关闭python 脚本已停止