From 3121e2f454e5da2f5e6578ae0e0224b3c0a48090 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81kos=20V=C3=A1rady?= Date: Wed, 22 Dec 2021 08:28:08 +0100 Subject: [PATCH] Reformatted codebase (#325) All python scripts are now reformatted with 'black' using line length of 100. Co-authored-by: Akos Varady --- auto_cpufreq/core.py | 86 ++++++++++--------------- auto_cpufreq/power_helper.py | 107 ++++++++++++++++++++++---------- auto_cpufreq/tlp_stat_parser.py | 3 +- setup.py | 35 ++++++----- 4 files changed, 125 insertions(+), 106 deletions(-) diff --git a/auto_cpufreq/core.py b/auto_cpufreq/core.py index cf826fdb..3d8e6deb 100644 --- a/auto_cpufreq/core.py +++ b/auto_cpufreq/core.py @@ -17,7 +17,7 @@ from shutil import which from subprocess import getoutput, call, run, check_output, DEVNULL -sys.path.append('../') +sys.path.append("../") from auto_cpufreq.power_helper import * warnings.filterwarnings("ignore") @@ -65,8 +65,9 @@ def file_stats(): auto_cpufreq_stats_file = open(auto_cpufreq_stats_path, "w") sys.stdout = auto_cpufreq_stats_file -def get_config(config_file=''): - if not hasattr(get_config, 'dict'): + +def get_config(config_file=""): + if not hasattr(get_config, "dict"): get_config.dict = dict() config = configparser.ConfigParser() @@ -77,6 +78,7 @@ def get_config(config_file=''): return get_config.dict + # get distro name try: dist_name = distro.id() @@ -85,8 +87,12 @@ def get_config(config_file=''): print("Warning: Cannot get distro name") if os.path.exists("/etc/pop-os/os-release"): print("Pop!_OS detected") - print("Pop!_OS uses a symbolic link for the os-release file, this causes issues and can be fixed by converting to a hard link") - print("Attempting to change symlink to hard link for /etc/os-release -> /etc/pop-os/os-release") + print( + "Pop!_OS uses a symbolic link for the os-release file, this causes issues and can be fixed by converting to a hard link" + ) + print( + "Attempting to change symlink to hard link for /etc/os-release -> /etc/pop-os/os-release" + ) yN = input("Continue? [y/N] ") if yN.lower() == "y": @@ -238,6 +244,7 @@ def charging(): # we cannot determine discharging state, assume we are on powercable return True + def get_avail_gov(): f = Path("/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors") return f.read_text().strip().split(" ") @@ -278,13 +285,9 @@ def cpufreqctl(): else: # deploy cpufreqctl.auto-cpufreq script if os.path.isfile("/usr/bin/cpufreqctl"): - shutil.copy( - SCRIPTS_DIR / "cpufreqctl.sh", "/usr/bin/cpufreqctl.auto-cpufreq" - ) + shutil.copy(SCRIPTS_DIR / "cpufreqctl.sh", "/usr/bin/cpufreqctl.auto-cpufreq") else: - shutil.copy( - SCRIPTS_DIR / "cpufreqctl.sh", "/usr/bin/cpufreqctl.auto-cpufreq" - ) + shutil.copy(SCRIPTS_DIR / "cpufreqctl.sh", "/usr/bin/cpufreqctl.auto-cpufreq") def cpufreqctl_restore(): @@ -312,17 +315,9 @@ def daemon_not_found(): def deploy_complete_msg(): - print( - "\n" - + "-" * 17 - + " auto-cpufreq daemon installed and running " - + "-" * 17 - + "\n" - ) + print("\n" + "-" * 17 + " auto-cpufreq daemon installed and running " + "-" * 17 + "\n") print("To view live stats, run:\nauto-cpufreq --stats") - print( - "\nTo disable and remove auto-cpufreq daemon, run:\nsudo auto-cpufreq --remove" - ) + print("\nTo disable and remove auto-cpufreq daemon, run:\nsudo auto-cpufreq --remove") footer() @@ -351,9 +346,7 @@ def deploy_daemon(): auto_cpufreq_stats_path.touch(exist_ok=True) print("\n* Deploy auto-cpufreq install script") - shutil.copy( - SCRIPTS_DIR / "auto-cpufreq-install.sh", "/usr/bin/auto-cpufreq-install" - ) + shutil.copy(SCRIPTS_DIR / "auto-cpufreq-install.sh", "/usr/bin/auto-cpufreq-install") print("\n* Deploy auto-cpufreq remove script") shutil.copy(SCRIPTS_DIR / "auto-cpufreq-remove.sh", "/usr/bin/auto-cpufreq-remove") @@ -367,6 +360,7 @@ def deploy_daemon(): call("/usr/bin/auto-cpufreq-install", shell=True) + # remove auto-cpufreq daemon def remove(): @@ -400,19 +394,13 @@ def remove(): # restore original cpufrectl script cpufreqctl_restore() + def gov_check(): for gov in get_avail_gov(): if gov not in ALL_GOVERNORS: - print( - "\n" - + "-" * 18 - + " Checking for necessary scaling governors " - + "-" * 19 - + "\n" - ) - sys.exit( - "ERROR:\n\nCouldn't find any of the necessary scaling governors.\n" - ) + print("\n" + "-" * 18 + " Checking for necessary scaling governors " + "-" * 19 + "\n") + sys.exit("ERROR:\n\nCouldn't find any of the necessary scaling governors.\n") + # root check func def root_check(): @@ -474,11 +462,8 @@ def set_powersave(): print(f'Setting to use: "{gov}" governor') run(f"cpufreqctl.auto-cpufreq --governor --set={gov}", shell=True) if ( - Path( - "/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference" - ).exists() - and Path("/sys/devices/system/cpu/intel_pstate/hwp_dynamic_boost").exists() - is False + Path("/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference").exists() + and Path("/sys/devices/system/cpu/intel_pstate/hwp_dynamic_boost").exists() is False ): run("cpufreqctl.auto-cpufreq --epp --set=balance_power", shell=True) print('Setting to use: "balance_power" EPP') @@ -686,11 +671,8 @@ def set_performance(): shell=True, ) if ( - Path( - "/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference" - ).exists() - and Path("/sys/devices/system/cpu/intel_pstate/hwp_dynamic_boost").exists() - is False + Path("/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference").exists() + and Path("/sys/devices/system/cpu/intel_pstate/hwp_dynamic_boost").exists() is False ): run("cpufreqctl.auto-cpufreq --epp --set=balance_performance", shell=True) print('Setting to use: "balance_performance" EPP') @@ -949,10 +931,10 @@ def distro_info(): with open("/var/lib/snapd/hostfs/etc/os-release", "r") as searchfile: for line in searchfile: if line.startswith("NAME="): - dist = line[5:line.find("$")].strip('"') + dist = line[5 : line.find("$")].strip('"') continue elif line.startswith("VERSION="): - version = line[8:line.find("$")].strip('"') + version = line[8 : line.find("$")].strip('"') continue except PermissionError as e: print(repr(e)) @@ -1002,9 +984,7 @@ def sysinfo(): print(f"CPU min frequency: {min_freq:.0f} MHz\n") # get coreid's and frequencies of online cpus by parsing /proc/cpuinfo - coreid_info = getoutput("egrep 'processor|cpu MHz|core id' /proc/cpuinfo").split( - "\n" - ) + coreid_info = getoutput("egrep 'processor|cpu MHz|core id' /proc/cpuinfo").split("\n") cpu_core = dict() freq_per_cpu = [] for i in range(0, len(coreid_info), 3): @@ -1043,9 +1023,7 @@ def sysinfo(): pass print("Core\tUsage\tTemperature\tFrequency") - for (cpu, usage, freq, temp) in zip( - cpu_core, usage_per_cpu, freq_per_cpu, temp_per_cpu - ): + for (cpu, usage, freq, temp) in zip(cpu_core, usage_per_cpu, freq_per_cpu, temp_per_cpu): print(f"CPU{cpu}:\t{usage:>5.1f}% {temp:>3.0f} °C {freq:>5.0f} MHz") if offline_cpus: @@ -1087,13 +1065,15 @@ def is_running(program, argument): if argument in p.cmdline(): return True + def daemon_running_msg(): print("\n" + "-" * 24 + " auto-cpufreq running " + "-" * 30 + "\n") print( - 'ERROR: auto-cpufreq is running in daemon mode.\n\nMake sure to stop the deamon before running with --live or --monitor mode' + "ERROR: auto-cpufreq is running in daemon mode.\n\nMake sure to stop the deamon before running with --live or --monitor mode" ) footer() + # check if auto-cpufreq --daemon is running def running_daemon(): if is_running("auto-cpufreq", "--daemon"): diff --git a/auto_cpufreq/power_helper.py b/auto_cpufreq/power_helper.py index c81acf09..ff5b8e1d 100644 --- a/auto_cpufreq/power_helper.py +++ b/auto_cpufreq/power_helper.py @@ -4,35 +4,41 @@ import os, sys, click from subprocess import getoutput, call, run, check_output, DEVNULL -sys.path.append('../') +sys.path.append("../") from auto_cpufreq.core import * from auto_cpufreq.tlp_stat_parser import TLPStatusParser # app_name var if sys.argv[0] == "power_helper.py": - app_name="python3 power_helper.py" + app_name = "python3 power_helper.py" else: - app_name="auto-cpufreq" + app_name = "auto-cpufreq" + def header(): print("\n------------------------- auto-cpufreq: Power helper -------------------------\n") + def helper_opts(): print("\nFor full list of options run: python3 power_helper.py --help") + # used to check if binary exists on the system def does_command_exists(cmd): return which(cmd) is not None + systemctl_exists = does_command_exists("systemctl") bluetoothctl_exists = does_command_exists("bluetoothctl") tlp_stat_exists = does_command_exists("tlp-stat") # detect if gnome power profile service is running -if os.getenv('PKG_MARKER') != "SNAP": +if os.getenv("PKG_MARKER") != "SNAP": if systemctl_exists: try: - gnome_power_status = call(["systemctl", "is-active", "--quiet", "power-profiles-daemon"]) + gnome_power_status = call( + ["systemctl", "is-active", "--quiet", "power-profiles-daemon"] + ) except: print("\nUnable to determine init system") print("If this causes any problems, please submit an issue:") @@ -44,10 +50,17 @@ def tlp_service_detect(): status_output = getoutput("tlp-stat -s") tlp_status = TLPStatusParser(status_output) if tlp_status.is_enabled(): - print("\n----------------------------------- Warning -----------------------------------\n") + print( + "\n----------------------------------- Warning -----------------------------------\n" + ) print("Detected you are running a TLP service!") - print("This daemon might interfere with auto-cpufreq which can lead to unexpected results.") - print("We strongly encourage you to remove TLP unless you really know what you are doing.") + print( + "This daemon might interfere with auto-cpufreq which can lead to unexpected results." + ) + print( + "We strongly encourage you to remove TLP unless you really know what you are doing." + ) + # alert about TLP when using snap def tlp_service_detect_snap(): @@ -56,11 +69,14 @@ def tlp_service_detect_snap(): print("This daemon might interfere with auto-cpufreq which can lead to unexpected results.") print("We strongly encourage you not to use TLP unless you really know what you are doing.") + # alert in case gnome power profile service is running def gnome_power_detect(): if systemctl_exists: if gnome_power_status == 0: - print("\n----------------------------------- Warning -----------------------------------\n") + print( + "\n----------------------------------- Warning -----------------------------------\n" + ) print("Detected running GNOME Power Profiles daemon service!") print("This daemon might interfere with auto-cpufreq and should be disabled.") print("\nSteps to perform this action using auto-cpufreq: power_helper script:") @@ -73,26 +89,29 @@ def gnome_power_detect(): def gnome_power_detect_install(): if systemctl_exists: if gnome_power_status == 0: - print("\n----------------------------------- Warning -----------------------------------\n") + print( + "\n----------------------------------- Warning -----------------------------------\n" + ) print("Detected running GNOME Power Profiles daemon service!") print("This daemon might interfere with auto-cpufreq and has been disabled.\n") - print("Disabled daemon is not automatically disabled in \"live\" and \"monitor\" mode and") + print('Disabled daemon is not automatically disabled in "live" and "monitor" mode and') print("will be enabled after auto-cpufreq is removed.") + # notification on snap def gnome_power_detect_snap(): - print("\n----------------------------------- Warning -----------------------------------\n") - print("Unable to detect state of GNOME Power Profiles daemon service!") - print("This daemon might interfere with auto-cpufreq and should be disabled.") - print("\nSteps to perform this action using auto-cpufreq: power_helper script:") - print("git clone https://github.com/AdnanHodzic/auto-cpufreq.git") - print("cd auto-cpufreq/auto_cpufreq") - print("python3 power_helper.py --gnome_power_disable") + print("\n----------------------------------- Warning -----------------------------------\n") + print("Unable to detect state of GNOME Power Profiles daemon service!") + print("This daemon might interfere with auto-cpufreq and should be disabled.") + print("\nSteps to perform this action using auto-cpufreq: power_helper script:") + print("git clone https://github.com/AdnanHodzic/auto-cpufreq.git") + print("cd auto-cpufreq/auto_cpufreq") + print("python3 power_helper.py --gnome_power_disable") # disable gnome >= 40 power profiles (live) def gnome_power_disable_live(): - if(gnome_power_status == 0): + if gnome_power_status == 0: call(["systemctl", "stop", "power-profiles-daemon"]) @@ -136,7 +155,7 @@ def gnome_power_svc_status(): print("\nUnable to see GNOME power profiles status") print("If this causes any problems, please submit an issue:") print("https://github.com/AdnanHodzic/auto-cpufreq/issues") - + # disable bluetooth on boot def bluetooth_disable(): @@ -156,7 +175,9 @@ def bluetooth_disable(): except Exception as e: print(f"\nERROR:\nWas unable to turn off bluetooth on boot\n{repr(e)}") else: - print("* Turn off bluetooth on boot [skipping] (package providing bluetooth access is not present)") + print( + "* Turn off bluetooth on boot [skipping] (package providing bluetooth access is not present)" + ) # enable bluetooth on boot @@ -177,7 +198,9 @@ def bluetooth_enable(): except Exception as e: print(f"\nERROR:\nWas unable to turn on bluetooth on boot\n{repr(e)}") else: - print("* Turn on bluetooth on boot [skipping] (package providing bluetooth access is not present)") + print( + "* Turn on bluetooth on boot [skipping] (package providing bluetooth access is not present)" + ) # turn off bluetooth on snap message @@ -186,28 +209,33 @@ def bluetooth_notif_snap(): print("\nSteps to perform this action using auto-cpufreq: power_helper script:") print("python3 power_helper.py --bluetooth_boot_off") + # turn off bluetooth on snap message def bluetooth_on_notif_snap(): print("\n* Unable to turn on bluetooth on boot due to Snap package restrictions!") print("\nSteps to perform this action using auto-cpufreq: power_helper script:") print("python3 power_helper.py --bluetooth_boot_on") + # gnome power removal reminder def gnome_power_rm_reminder(): if systemctl_exists: if gnome_power_status != 0: - print("\n----------------------------------- Warning -----------------------------------\n") + print( + "\n----------------------------------- Warning -----------------------------------\n" + ) print("Detected GNOME Power Profiles daemon service is stopped!") print("This service will now be enabled and started again.") + def gnome_power_rm_reminder_snap(): - print("\n----------------------------------- Warning -----------------------------------\n") - print("Unable to detect state of GNOME Power Profiles daemon service!") - print("Now it's recommended to enable this service.") - print("\nSteps to perform this action using auto-cpufreq: power_helper script:") - print("git clone https://github.com/AdnanHodzic/auto-cpufreq.git") - print("cd auto-cpufreq/auto_cpufreq") - print("python3 power_helper.py --gnome_power_enable") + print("\n----------------------------------- Warning -----------------------------------\n") + print("Unable to detect state of GNOME Power Profiles daemon service!") + print("Now it's recommended to enable this service.") + print("\nSteps to perform this action using auto-cpufreq: power_helper script:") + print("git clone https://github.com/AdnanHodzic/auto-cpufreq.git") + print("cd auto-cpufreq/auto_cpufreq") + print("python3 power_helper.py --gnome_power_enable") def valid_options(): @@ -219,15 +247,25 @@ def valid_options(): @click.command() @click.option("--gnome_power_enable", is_flag=True, help="Enable GNOME Power profiles service") @click.option("--gnome_power_disable", is_flag=True, help="Disable GNOME Power profiles service") -@click.option("--gnome_power_status", is_flag=True, help="Get status of GNOME Power profiles service") +@click.option( + "--gnome_power_status", is_flag=True, help="Get status of GNOME Power profiles service" +) @click.option("--bluetooth_boot_on", is_flag=True, help="Turn on Bluetooth on boot") @click.option("--bluetooth_boot_off", is_flag=True, help="Turn off Bluetooth on boot") -def main(gnome_power_enable, gnome_power_disable, gnome_power_status, bluetooth_boot_off, bluetooth_boot_on): +def main( + gnome_power_enable, + gnome_power_disable, + gnome_power_status, + bluetooth_boot_off, + bluetooth_boot_on, +): root_check() if len(sys.argv) == 1: header() - print("Unrecognized option!\n\nRun: \"" + app_name + " --help\" for list of available options.") + print( + 'Unrecognized option!\n\nRun: "' + app_name + ' --help" for list of available options.' + ) footer() else: if gnome_power_enable: @@ -261,5 +299,6 @@ def main(gnome_power_enable, gnome_power_disable, gnome_power_status, bluetooth_ helper_opts() footer() -if __name__ == '__main__': + +if __name__ == "__main__": main() diff --git a/auto_cpufreq/tlp_stat_parser.py b/auto_cpufreq/tlp_stat_parser.py index 43bc9eab..003ac2c6 100644 --- a/auto_cpufreq/tlp_stat_parser.py +++ b/auto_cpufreq/tlp_stat_parser.py @@ -1,4 +1,4 @@ -class TLPStatusParser(): +class TLPStatusParser: def __init__(self, tlp_stat_output): self.data = {} self._parse(tlp_stat_output) @@ -17,4 +17,3 @@ def _get_key(self, key): def is_enabled(self): return self._get_key("state") == "enabled" - diff --git a/setup.py b/setup.py index dbd44bfe..6c542b6e 100644 --- a/setup.py +++ b/setup.py @@ -2,34 +2,35 @@ from setuptools import setup -with open('README.md') as readme_file: +with open("README.md") as readme_file: readme = readme_file.read() this = os.path.dirname(os.path.realpath(__file__)) + def read(name): with open(os.path.join(this, name)) as f: return f.read() + + setup( - name='auto-cpufreq', - version='1.0', - description='Automatic CPU speed & power optimizer for Linux', + name="auto-cpufreq", + version="1.0", + description="Automatic CPU speed & power optimizer for Linux", long_description=readme, - author='Adnan Hodzic', - author_email='adnan@hodzic.org', - url='https://github.com/AdnanHodzic/auto-cpufreq', - packages=['auto_cpufreq'], - install_requires=read('requirements.txt'), + author="Adnan Hodzic", + author_email="adnan@hodzic.org", + url="https://github.com/AdnanHodzic/auto-cpufreq", + packages=["auto_cpufreq"], + install_requires=read("requirements.txt"), include_package_data=True, zip_safe=True, - license='GPLv3', - keywords='linux cpu speed power frequency turbo optimzier auto cpufreq', + license="GPLv3", + keywords="linux cpu speed power frequency turbo optimzier auto cpufreq", classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Intended Audience :: Developers', - 'Operating System :: POSIX :: Linux' - 'Environment :: Console' - 'Natural Language :: English' + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Operating System :: POSIX :: Linux" "Environment :: Console" "Natural Language :: English", ], - scripts=['bin/auto-cpufreq'] + scripts=["bin/auto-cpufreq"], )