0

I'm making a python program that should force kill the current program using pid. It is designed to be run with AHK. I am on windows 10.

I assigned "os.getpid()" to "pid" I have tried using the

os.kill(pid,signal.SIGKILL)

command to kill the pid of the program, but this command only works on Linux.

I found another viable solution, using the

os.system("taskkill /f /pid ") 

command. My problem lies with this command. I cannot figure out how to format it to use the variable "pid" that I assigned eariler.

Here is my code:

import os
import signal

pid = os.getpid()
os.system("taskkill /f /pid" "pid")

This format did not work. I need help with the formatting of the "os.system("taskkill /f /pid" "pid") command. (i also tried "os.system("taskkill /f /pid" os.getpid()))

The code should have killed the python shell that I was using for testing. (but it didn't)

ghost007
  • 3
  • 2
  • I plan to use this to quickly kill a full screen application (like a video game). I am aware that there are tools that can do this but i wanted to make one myself. – ghost007 Jun 04 '19 at 01:04

2 Answers2

1

"pid" is just a string that consists of three characters. You should embed the value of the variable pid into the command line:

os.system(f"ftaskkill /f /pid {pid}")

If you use an older Python, try

os.system("ftaskkill /f /pid {}".format(pid))
DYZ
  • 55,249
  • 10
  • 64
  • 93
  • it was this but using the code "os.system("taskkill /f /pid {}".format(pid))" – ghost007 Jun 04 '19 at 01:33
  • In Windows, `os.kill(pid, signal)` is implemented via `TerminateProcess(hProcess, signal)`, but only for values of `signal` other than 0 and 1. The value of `signal` is used as the process exit status. We'd like this to be 1 typically for a forced termination, but `os.kill` is badly designed, so just use 3. What doesn't exist is `signal.SIGKILL` since Windows does not have or use kernel signals, unlike POSIX systems. (It has rough equivalents such as APCs, ALPC messages, window messages, and console events, but nothing that exactly maps to POSIX signals.) – Eryk Sun Jun 04 '19 at 09:37
  • In this answer, "ftaskkill" should be "taskkill". It's not ideal to use `os.system` since spawning a console application such as cmd.exe or taskkill.exe will briefly flash a console window when run from a GUI app that has no console to inherit. Best to use `subprocess.call` with `creationflags=CREATE_NO_WINDOW` (e.g. see [this answer](https://stackoverflow.com/a/7006424/205580)). – Eryk Sun Jun 04 '19 at 09:42
0

Maybe its because pid is a string,

idk if i am right but try

os.system("taskkill /f " + pid)

vaku
  • 697
  • 8
  • 17