终止包含 python 脚本的批处理文件

Kill a batch file containing the python script within

我有问题。我需要使用驻留在同一个批处理文件中的 python 脚本来终止该批处理文件。批处理文件将 abc.py 脚本作为第一个脚本以及其他脚本。所以我需要杀死批处理文件,这样其他人就不会被执行。这是我尝试过的:

for proc in psutil.process_iter():
     if proc.name() == "python.exe" and len(proc.cmdline()) > 1 and 
         "abc.py" in proc.cmdline()[1]:
    proc.terminate()

但这只会杀死 python 脚本,不会杀死批处理文件。尝试用同样的效果杀死 pid。

os.system("taskkill /F /PID " + str(os.getpid()))

编辑 1 该脚本检查是否存在另一个 运行 脚本,然后需要自行终止。

您的批处理文件将需要检查最后一个命令是否成功,如果没有成功则退出。

How do I make a batch file terminate upon encountering an error?

如果你只是想杀死你的 parent 是谁,那很简单:只需使用 os.getppid() 而不是 os.getpid():

os.system("taskkill /F /PID " + str(os.getppid()))

当然,出于所有常见原因,最好使用 subprocess 而不是 os.system,比如在失败时得到一个有用的错误:

subprocess.run(['taskkill', '/F', '/PID', str(os.getppid())])

或者,更好的是,不要使用 taskkill,只是 kill it directly. This also gives you the option of using a nicer Ctrl-C or Ctrl-Break 杀死而不是硬杀死,如果愿意的话:

os.kill(os.getppid(), signal.CTRL_BREAK_EVENT)

如果您使用的是 Python 2.7,getppid 不适用于 Windows;仅在 3.2 中添加。 (而且我认为 os.kill 也是如此,signal.CTRL_BREAK_EVENT 也是如此。)

由于您已经parent能够使用psutil,您可以使用它。

不需要遍历系统的每一个进程来寻找自己,只需要构建一个默认的Process. And you can go from any process to its parent with parent. And then you can use the kill or terminate

proc = psutil.Process().parent()
proc.kill()

以上所有,除了使用 CTRL_C_EVENTCTRL_BREAK_EVENT 而不是标准信号),都具有 cross-platform 的优点——您可以 运行 Linux 或 macOS 或其他任何系统上的相同脚本,它会杀死 运行 它的 shell 脚本。