38 lines
1.5 KiB
Python
38 lines
1.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Strict JSON interface to powerprofilesctl, without shell execution."""
|
|
import json
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
|
|
PROFILES = ('power-saver', 'balanced', 'performance')
|
|
|
|
|
|
def execute(argv, runner=subprocess.run, which=shutil.which):
|
|
if not which('powerprofilesctl'):
|
|
return {'ok': False, 'error': 'powerprofilesctl не установлен'}
|
|
if len(argv) == 1 and argv[0] == 'get':
|
|
args = ['powerprofilesctl', 'get']
|
|
elif len(argv) == 2 and argv[0] == 'set' and argv[1] in PROFILES:
|
|
args = ['powerprofilesctl', 'set', argv[1]]
|
|
else:
|
|
return {'ok': False, 'error': 'Недопустимая команда или профиль'}
|
|
try:
|
|
result = runner(args, capture_output=True, text=True, timeout=12, check=False)
|
|
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
return {'ok': False, 'error': str(exc)[:300]}
|
|
if result.returncode:
|
|
return {'ok': False, 'error': (result.stderr or result.stdout or 'Команда завершилась с ошибкой').strip()[:300]}
|
|
if argv[0] == 'get':
|
|
profile = result.stdout.strip()
|
|
if profile not in PROFILES:
|
|
return {'ok': False, 'error': 'Неизвестный профиль: ' + profile[:100]}
|
|
return {'ok': True, 'profile': profile}
|
|
return {'ok': True, 'profile': argv[1]}
|
|
|
|
|
|
if __name__ == '__main__':
|
|
response = execute(sys.argv[1:])
|
|
print(json.dumps(response, ensure_ascii=False))
|
|
sys.exit(0 if response['ok'] else 1)
|