繁体   English   中英

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

[英]Python, close subprocess with different SID when script ends

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

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


有什么方法可以杀死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列表。 这给我带来了很多其他问题(例如,在使用shell时使用.terminate()变得更加复杂,并且需要具有其会话ID,请参见此处

只需将cmd从字符串拆分为args列表,就可以使用Popen.terminate()而不用赋予其自己的会话ID,因为没有单独的会话ID,所以当python脚本停止运行时,该过程将关闭

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM