Skip to content

Instantly share code, notes, and snippets.

@juancarlospaco
Last active April 6, 2018 19:37
Show Gist options
  • Save juancarlospaco/e53a1937a72008b4e11a to your computer and use it in GitHub Desktop.
Save juancarlospaco/e53a1937a72008b4e11a to your computer and use it in GitHub Desktop.
Set Smooth CPUs Priority and set Process Name. Linux only.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import logging as log
from ctypes import byref, cdll, create_string_buffer
def set_process_name_and_cpu_priority(name):
"""Set process name and cpu priority.
>>> set_process_name_and_cpu_priority("test_test")
True
"""
try:
os.nice(19) # smooth cpu priority
libc = cdll.LoadLibrary("libc.so.6") # set process name
buff = create_string_buffer(len(name.lower().strip()) + 1)
buff.value = bytes(name.lower().strip().encode("utf-8"))
libc.prctl(15, byref(buff), 0, 0, 0)
except Exception:
return False # this may fail on windows and its normal, so be silent.
else:
log.debug("Process Name set to: {0}.".format(name))
return True
if __name__ in '__main__':
log.basicConfig(level=-1) # basic logger
set_process_name_and_cpu_priority("your_app_name_here")
__import__("doctest").testmod(verbose=True, report=True, exclude_empty=1)
@juancarlospaco
Copy link
Author

Instead of python file.py on the Process List will appear as your_app_name_here

juan@z:~$ python2 temp.py 

Process Name set to: your_app_name_here.
Simulating App running, check System Monitor to see process name.
Trying:
    set_process_name_and_cpu_priority("test_test")
Expecting:
    True
DEBUG:root:Process Name set to: test_test.
ok
1 items passed all tests:
   1 tests in __main__.set_process_name_and_cpu_priority
1 tests in 1 items.
1 passed and 0 failed.
Test passed.

juan@z:~$ python3 temp.py

Process Name set to: your_app_name_here.
Simulating App running, check System Monitor to see process name.
Trying:
    set_process_name_and_cpu_priority("test_test")
Expecting:
    True
DEBUG:root:Process Name set to: test_test.
ok
1 items passed all tests:
   1 tests in __main__.set_process_name_and_cpu_priority
1 tests in 1 items.
1 passed and 0 failed.
Test passed.

juan@z:~$

Note:

  • Edit the string "your_app_name_here" with the App name.
  • libc.so.6 is NOT a file path, is a Lib Name.
  • try: ... except: is needed because the code block is expected to fail on MS Window, and thats Ok.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment