Robert Seifert
Robert Seifert

Reputation: 25232

Kill all python main processes apart from current one

Consider the following script:

import matplotlib.pyplot as plt

plt.plot([1,2,3], [1,2,3])
plt.show()

Everytime you run it, it creates a new figure within a new python.exe process, if you don't close the figure before. But I want to close all previous open figures (it's just an example, please no matplotlib solutions), means all previous opened processes.

This is my approach:

  1. get current process ID with os
  2. get all process IDs related to python with psutil
  3. filter out current ID from all python IDs
  4. kill remaining list of IDs

import os
currentId = os.getpid()

import psutil
allPyIds = [p.pid for p in psutil.process_iter() if "python" in str(p.name)]

PyIdsToKill = [x for x in allPyIds if x != currentId]
for PyId in PyIdsToKill:
    os.kill(PyId, 1)

It works, it closes all open python processes apart from the current one. However I get the following error, when there are actually processes to close:

Traceback (most recent call last): File "C:....py", line 10, in for PyId in PyIdsToKill: OSError: [WinError 87] Falscher Parameter [Finished in 0.3s with exit code 1]

What is my mistake?


I'm running on Windows 7 Pro:

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32

Upvotes: 2

Views: 1970

Answers (3)

Stephan Semerad
Stephan Semerad

Reputation: 91

Not sure if this will help you, but I managed to kill all process apart from the current one by getting the pid, but when I run the code from atom, 2 processes start. so I had to match by date aswell for the one where the PID didnt match.

happy coding.

import re, datetime, psutil, os
print('current process: '+str(os.getpid()))
for process in psutil.process_iter():
    if str(process.pid) == str(os.getpid()):
        current_started = re.findall(r'\d{1,2}:\d{1,2}:\d{1,2}', str(process))[0]

for process in psutil.process_iter():
    if "python.exe" in str(process.name):
        if str(process.pid) != str(os.getpid()):
            if str(current_started)!= re.findall(r'\d{1,2}:\d{1,2}:\d{1,2}', str(process))[0]:
                os.system("Taskkill /PID "+str(process.pid)+"")

Upvotes: 0

user2804197
user2804197

Reputation: 402

You could also use taskkill if you do not aim for cross-platform compatibility:

Is it possible to kill a process on Windows from within Python?

import os
PyIds = [int(line.split()[1]) for line in os.popen('tasklist').readlines()[3:] if line.split()[0] == "python.exe"]
PyIdsToKill = [id for id in PyIds if id != os.getpid()]
for pid in PyIdsToKill:
    os.system("taskkill /pid %i" % pid)

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249143

You have hard-coded the signal 1 in os.kill. What is 1 supposed to be? On Unix it would be SIGHUP but there is no such thing on Windows. I suggest using the constants defined in the signal module, like so:

os.kill(PyId, signal.SIGTERM)

You could also consider using signal.SIGINT.

Upvotes: 1

Related Questions