get system cpu frequency in python

Here's an example code snippet that uses the subprocess module to get the CPU frequency on a Linux-based system:

main.py
import subprocess

def get_cpu_frequency():
    cmd = "cat /proc/cpuinfo | grep 'cpu MHz' | awk '{print $4}'"
    output = subprocess.check_output(cmd, shell=True).strip().decode()
    return float(output)

print(get_cpu_frequency())
234 chars
9 lines

This code reads the CPU frequency from the file /proc/cpuinfo, which contains various information about the system's CPU(s). The grep command filters out the line(s) containing the string "cpu MHz", which indicates the CPU frequency. The awk command then extracts the fourth field (i.e., the numeric value) from each line. Finally, the code converts the output to a float and returns it.

Note that this code assumes that the system is running Linux, and that /proc/cpuinfo is accessible.

gistlibby LogSnag