Skip to content

Instantly share code, notes, and snippets.

@donno2048
Created January 9, 2022 12:36
Show Gist options
  • Save donno2048/d29e3094367349344adabd68ce768e3e to your computer and use it in GitHub Desktop.
Save donno2048/d29e3094367349344adabd68ce768e3e to your computer and use it in GitHub Desktop.
from os.path import isdir
def cpu_count() -> int:
i = 0
while isdir('/sys/devices/system/cpu/cpu%d' % i): i += 1
return i
def __check_cpu(i: int) -> None:
assert i < cpu_count(), "CPU index out of range"
assert isinstance(i, int), "CPU index must be an integer"
assert i > 0, "CPU 0 is always active and cannot be deactivated nor activated"
def cpu_active(i: int) -> bool:
if not i: return True
__check_cpu(i)
try: return bool(int(open('/sys/devices/system/cpu/cpu%d/online' % i).read().strip()))
except PermissionError: print('Permission denied')
def cpu_activate(i: int) -> None:
__check_cpu(i)
try: open('/sys/devices/system/cpu/cpu%d/online' % i, 'w').write('1')
except PermissionError: print('Permission denied')
def cpu_deactivate(i: int) -> None:
__check_cpu(i)
try: open('/sys/devices/system/cpu/cpu%d/online' % i, 'w').write('0')
except PermissionError: print('Permission denied')
def cpu_toggle(i: int) -> None:
__check_cpu(i)
try: open('/sys/devices/system/cpu/cpu%d/online' % i, 'w').write(str(int(not cpu_active(i))))
except PermissionError: print('Permission denied')
def cpu_set(i: int, state: bool) -> None:
__check_cpu(i)
try: open('/sys/devices/system/cpu/cpu%d/online' % i, 'w').write(str(int(state)))
except PermissionError: print('Permission denied')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment