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:
- get current process ID with
os
- get all process IDs related to python with
psutil
- filter out current ID from all python IDs
- 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