跳至内容

Kill

运行 icommand 时,它会在一个单独的进程组中运行。当它被杀死时,整个进程组会被杀死。

对于普通进程,这不会改变任何事情。

对于启动子进程的进程,这意味着它们的子进程及其子进程会被杀死。

child.py

import os
import time

# Write out pid of this process so we can check if it is still alive
with open("child.pid", "w") as handle:
    handle.write(str(os.getpid()))

time.sleep(1)
parent.py

import os
import sys
import time
import subprocess

# Write out pid of this process so we can check if it is still alive
with open("parent.pid", "w") as handle:
    handle.write(str(os.getpid()))

# Run child.py with the same python used to run parent.py
subprocess.call([sys.executable, "child.py"])

# This process will get killed after 0.5 seconds by first
# test but exit on its own by second.
time.sleep(1)

print("I got to the end!")

使用代码

from icommandlib import ICommand
from commandlib import python
import time

正常

process = ICommand(python("parent.py")).run()
time.sleep(0.5)
process.kill()
  • 当代码运行到完成时。

将导致这些文件名中的进程不再处于活动状态

  • parent.pid

  • child.pid

在 kill 之前意外死亡

process = ICommand(python("parent.py")).run()
time.sleep(2.5)
process.kill()

将引发类型为 icommandlib.exceptions.UnexpectedExit 的异常,并显示消息

Process unexpectedly exited with exit code 0. Output:
I got to the end!

预期在 kill 之前完成

process = ICommand(python("parent.py")).run()
process.wait_for_successful_exit()
process.kill()

将引发类型为 icommandlib.exceptions.AlreadyExited 的异常,并显示消息

Process already exited with 0. Output:
I got to the end!

可执行规范

kill.story storytests 自动生成的文档。