Skip to content

Instantly share code, notes, and snippets.

@ryanpeach
Last active January 10, 2018 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanpeach/2990c6f98de3ea0f7909d3d39d971a84 to your computer and use it in GitHub Desktop.
Save ryanpeach/2990c6f98de3ea0f7909d3d39d971a84 to your computer and use it in GitHub Desktop.
Using wmctrl in Linux, close any windows who's titles are not recognized via a whitelist (with regex).
# coding: utf-8
import subprocess
import re
def get_windows():
list_of_windows = subprocess.check_output(["wmctrl","-l"]).split(b"\n")
meta_list_of_windows = [s.decode("utf-8").split() for s in list_of_windows if s]
user_processes = {}
for line in meta_list_of_windows:
n = int(line[1])
if n == 0:
user_processes[line[0]] = " ".join(line[3:])
return user_processes
def close_window(title):
return subprocess.call(["wmctrl","-c",title])
def get_whitelist(fname):
patterns = []
with open(fname, "r") as f:
for line in f:
patterns.append(re.compile(line.replace("\n","")))
return patterns
if __name__=="__main__":
import argparse
# Get arguments from user
parser = argparse.ArgumentParser(description="Using wmctrl in Linux, close any windows who's titles are not recognized via a whitelist (with regex).")
# Plotting Options
parser.add_argument('-f', '--fname', metavar='f', type=str, default="./whitelist.conf",
help='The file name and path of the whitelist.')
args = parser.parse_args()
user_processes = get_windows()
whitelist = get_whitelist(args.fname)
allowed = set()
for pattern in whitelist:
for k, v in user_processes.items():
if re.fullmatch(pattern, v) is not None:
allowed.add(k)
disallowed = set(user_processes.keys()) - allowed
for k in disallowed:
close_window(user_processes[k])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment