Last active
April 13, 2021 09:16
-
-
Save RaphaelMeudec/05e3f82d32990770fc2ac5f9bd289f35 to your computer and use it in GitHub Desktop.
Python script to automatically renice all python processes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
from datetime import datetime | |
import psutil | |
DEFAULT_DRAGO_NICENESS_VALUE = 5 | |
DURATION_BEFORE_RENICING = 30 | |
def renice_python_process(proc): | |
""" | |
Renice process to niceness=5 if it matches all conditions below: | |
- [x] is a python process | |
- [x] is not a root process | |
- [x] does not have a positive niceness | |
- [x] has started at least 3 min ago | |
""" | |
is_user_process = proc.username() != "root" | |
is_python_process = any(["python" in command_line_argument for command_line_argument in proc.cmdline()]) | |
is_niceness_stricly_positive = proc.nice() > 0 | |
is_process_old_enough = (datetime.now().timestamp() - proc.create_time()) > DURATION_BEFORE_RENICING | |
should_renice_process = ( | |
is_python_process | |
and is_user_process | |
and is_process_old_enough | |
and (not is_niceness_stricly_positive) | |
) | |
if should_renice_process: | |
print("renicing", proc) | |
proc.nice(DEFAULT_DRAGO_NICENESS_VALUE) | |
for thread in proc.threads(): | |
psutil.Process(thread.id).nice(DEFAULT_DRAGO_NICENESS_VALUE) | |
def renice_python_processes(): | |
""" Iterator with Exception catches for `renice_python_process` """ | |
for proc in psutil.process_iter(["cmdline", "username", "nice", "create_time"]): | |
try: | |
renice_python_process(proc) | |
except psutil.NoSuchProcess: | |
# Concurrently terminated | |
pass | |
except (psutil.AccessDenied , psutil.ZombieProcess): | |
print("Could not renice", proc) | |
if __name__ == "__main__": | |
renice_python_processes() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment