Search /proc/cpuinfo for a field and return its value, if found,
        otherwise None.
162647
def get_cpuinfo_field(self, field):
        
        # Match a line like 'Hardware   : BCM2709':
        pattern = r'^' + field + r'\s+:\s+(.*)$'

        with open('/proc/cpuinfo', 'r') as infile:
            cpuinfo = infile.read().split('\n')
            for line in cpuinfo:
                match = re.search(pattern, line, flags=re.IGNORECASE)
                if match:
                    return match.group(1)

        return None
762209
def _node_info(conn):
    '''
    
    '''
    raw = conn.getInfo()
    info = {'cpucores': raw[6],
            'cpumhz': raw[3],
            'cpumodel': six.text_type(raw[0]),
            'cpus': raw[2],
            'cputhreads': raw[7],
            'numanodes': raw[4],
            'phymemory': raw[1],
            'sockets': raw[5]}
    return info
985909
def get_value(self, name):
        """"""
        code = u"get_ipython().kernel.get_value('%s')" % name
        if self._reading:
            method = self.kernel_client.input
            code = u'!' + code
        else:
            method = self.silent_execute

        # Wait until the kernel returns the value
        wait_loop = QEventLoop()
        self.sig_got_reply.connect(wait_loop.quit)
        method(code)
        wait_loop.exec_()

        # Remove loop connection and loop
        self.sig_got_reply.disconnect(wait_loop.quit)
        wait_loop = None

        # Handle exceptions
        if self._kernel_value is None:
            if self._kernel_reply:
                msg = self._kernel_reply[:]
                self._kernel_reply = None
                raise ValueError(msg)

        return self._kernel_value
70888
def _parse_processor_embedded_health(self, data):
        
        processor = self.get_value_as_list((data['GET_EMBEDDED_HEALTH_DATA']
                                           ['PROCESSORS']), 'PROCESSOR')
        if processor is None:
            msg = "Unable to get cpu data. Error: Data missing"
            raise exception.IloError(msg)
        cpus = 0
        for proc in processor:
            for val in proc.values():
                processor_detail = val['VALUE']
                proc_core_threads = processor_detail.split('; ')
                for x in proc_core_threads:
                    if "thread" in x:
                        v = x.split()
                        try:
                            cpus = cpus + int(v[0])
                        except ValueError:
                            msg = ("Unable to get cpu data. "
                                   "The Value %s returned couldn't be "
                                   "manipulated to get number of "
                                   "actual processors" % processor_detail)
                            raise exception.IloError(msg)
        cpu_arch = 'x86_64'
        return cpus, cpu_arch
1057061
def ow_search(self, vid=0xBC, pid=None, name=None):
        """"""
        for m in self.get_mems(MemoryElement.TYPE_1W):
            if pid and m.pid == pid or name and m.name == name:
                return m

        return None
415203
def check_process_by_name(self, process):
        """"""
        status = False
        cmd_line_glob = "/proc/[0-9]*/cmdline"
        try:
            cmd_line_paths = glob.glob(cmd_line_glob)
            for path in cmd_line_paths:
                f = open(path, 'r')
                cmd_line = f.read().strip()
                if process in cmd_line:
                    status = True
        except IOError as e:
            return False
        return status
1366899
def _search_val(matches, compiled_pattern, fld_val):
        """"""
        mtch = compiled_pattern.search(fld_val)
        if mtch:
            matches.append(fld_val)
404225
def available_cpu_count() -> int:
    

    # cpuset
    # cpuset may restrict the number of *available* processors
    try:
        match = re.search(r'(?m)^Cpus_allowed:\s*(.*)$',
                          open('/proc/self/status').read())
        if match:
            res = bin(int(match.group(1).replace(',', ''), 16)).count('1')
            if res > 0:
                return res
    except IOError:
        LOG.debug("Could not get the number of allowed CPUs")

    # http://code.google.com/p/psutil/
    try:
        import psutil
        return psutil.cpu_count()  # psutil.NUM_CPUS on old versions
    except (ImportError, AttributeError):
        LOG.debug("Could not get the number of allowed CPUs")

    # POSIX
    try:
        res = int(os.sysconf('SC_NPROCESSORS_ONLN'))

        if res > 0:
            return res
    except (AttributeError, ValueError):
        LOG.debug("Could not get the number of allowed CPUs")

    # Linux
    try:
        res = open('/proc/cpuinfo').read().count('processor\t:')

        if res > 0:
            return res
    except IOError:
        LOG.debug("Could not get the number of allowed CPUs")

    raise Exception('Can not determine number of CPUs on this system')
1173978
def _get_cpu_info_from_kstat():
	'''
	
	'''
	try:
		# Just return {} if there is no isainfo or kstat
		if not DataSource.has_isainfo() or not DataSource.has_kstat():
			return {}

		# If isainfo fails return {}
		returncode, flag_output = DataSource.isainfo_vb()
		if flag_output == None or returncode != 0:
			return {}

		# If kstat fails return {}
		returncode, kstat = DataSource.kstat_m_cpu_info()
		if kstat == None or returncode != 0:
			return {}

		# Various fields
		vendor_id = kstat.split('\tvendor_id ')[1].split('\n')[0].strip()
		processor_brand = kstat.split('\tbrand ')[1].split('\n')[0].strip()
		stepping = int(kstat.split('\tstepping ')[1].split('\n')[0].strip())
		model = int(kstat.split('\tmodel ')[1].split('\n')[0].strip())
		family = int(kstat.split('\tfamily ')[1].split('\n')[0].strip())

		# Flags
		flags = flag_output.strip().split('\n')[-1].strip().lower().split()
		flags.sort()

		# Convert from GHz/MHz string to Hz
		scale = 6
		hz_advertised = kstat.split('\tclock_MHz ')[1].split('\n')[0].strip()
		hz_advertised = _to_decimal_string(hz_advertised)

		# Convert from GHz/MHz string to Hz
		hz_actual = kstat.split('\tcurrent_clock_Hz ')[1].split('\n')[0].strip()
		hz_actual = _to_decimal_string(hz_actual)

		info = {
		'vendor_id_raw' : vendor_id,
		'brand_raw' : processor_brand,

		'hz_advertised_friendly' : _hz_short_to_friendly(hz_advertised, scale),
		'hz_actual_friendly' : _hz_short_to_friendly(hz_actual, 0),
		'hz_advertised' : _hz_short_to_full(hz_advertised, scale),
		'hz_actual' : _hz_short_to_full(hz_actual, 0),

		'stepping' : stepping,
		'model' : model,
		'family' : family,
		'flags' : flags
		}

		info = {k: v for k, v in info.items() if v}
		return info
	except:
		return {}
137998
protected function _cpuinfo()
    {
        if (CommonFunctions::rfts('/proc/cpuinfo', $bufr)) {
            $cpulist = null;
            $raslist = null;

            // sparc
            if (preg_match('/\nCpu(\d+)Bogo\s*:/i', $bufr)) {
                $bufr = preg_replace('/\nCpu(\d+)ClkTck\s*:/i', "\nCpu0ClkTck:", preg_replace('/\nCpu(\d+)Bogo\s*:/i', "\n\nprocessor: $1\nCpu0Bogo:", $bufr));
            } else {
                $bufr = preg_replace('/\nCpu(\d+)ClkTck\s*:/i', "\n\nprocessor: $1\nCpu0ClkTck:", $bufr);
            }

            if (preg_match('/\nprocessor\s*:\s*\d+\r?\nprocessor\s*:\s*\d+/', $bufr)) {
                $bufr = preg_replace('/^(processor\s*:\s*\d+)\r?$/m', "$1\n", $bufr);
            }

            $processors = preg_split('/\s?\n\s?\n/', trim($bufr));

            //first stage
            $_arch = null;
            $_impl = null;
            $_part = null;
            $_hard = null;
            $_revi = null;
            $_cpus = null;
            $_buss = null;
            $procname = null;
            foreach ($processors as $processor) if (!preg_match('/^\s*processor\s*:/mi', $processor)) {
                $details = preg_split("/\n/", $processor, -1, PREG_SPLIT_NO_EMPTY);
                foreach ($details as $detail) {
                    $arrBuff = preg_split('/\s*:\s*/', trim($detail));
                    if ((count($arrBuff) == 2) && (($arrBuff1 = trim($arrBuff[1])) !== '')) {
                        switch (strtolower($arrBuff[0])) {
                        case 'cpu architecture':
                            $_arch = $arrBuff1;
                            break;
                        case 'cpu implementer':
                            $_impl = $arrBuff1;
                            break;
                        case 'cpu part':
                            $_part = $arrBuff1;
                            break;
                        case 'hardware':
                            $_hard = $arrBuff1;
                            break;
                        case 'revision':
                            $_revi = $arrBuff1;
                            break;
                        case 'cpu frequency':
                            if (preg_match('/^(\d+)\s+Hz/i', $arrBuff1, $bufr2)) {
                                $_cpus = round($bufr2[1]/1000000);
                            }
                            break;
                        case 'system bus frequency':
                            if (preg_match('/^(\d+)\s+Hz/i', $arrBuff1, $bufr2)) {
                                $_buss = round($bufr2[1]/1000000);
                            }
                            break;
                        case 'cpu':
                            $procname = $arrBuff1;
                            break;
                        }
                    }
                }
            }

            //second stage
            $cpucount = 0;
            $speedset = false;
            foreach ($processors as $processor) if (preg_match('/^\s*processor\s*:/mi', $processor)) {
                $proc = null;
                $arch = null;
                $impl = null;
                $part = null;
                $dev = new CpuDevice();
                $details = preg_split("/\n/", $processor, -1, PREG_SPLIT_NO_EMPTY);
                foreach ($details as $detail) {
                    $arrBuff = preg_split('/\s*:\s*/', trim($detail));
                    if ((count($arrBuff) == 2) && (($arrBuff1 = trim($arrBuff[1])) !== '')) {
                        switch (strtolower($arrBuff[0])) {
                        case 'processor':
                            $proc = $arrBuff1;
                            if (is_numeric($proc)) {
                                if (strlen($procname)>0) {
                                    $dev->setModel($procname);
                                }
                            } else {
                                $procname = $proc;
                                $dev->setModel($procname);
                            }
                            break;
                        case 'model name':
                        case 'cpu model':
                        case 'cpu type':
                        case 'cpu':
                            $dev->setModel($arrBuff1);
                            break;
                        case 'cpu mhz':
                        case 'clock':
                            if ($arrBuff1 > 0) { //openSUSE fix
                                $dev->setCpuSpeed($arrBuff1);
                                $speedset = true;
                            }
                            break;
                        case 'cycle frequency [hz]':
                            $dev->setCpuSpeed($arrBuff1 / 1000000);
                            $speedset = true;
                            break;
                        case 'cpu0clktck':
                            $dev->setCpuSpeed(hexdec($arrBuff1) / 1000000); // Linux sparc64
                            $speedset = true;
                            break;
                        case 'l3 cache':
                        case 'cache size':
                            $dev->setCache(trim(preg_replace("/[a-zA-Z]/", "", $arrBuff1)) * 1024);
                            break;
                        case 'initial bogomips':
                        case 'bogomips':
                        case 'cpu0bogo':
                            $dev->setBogomips(round($arrBuff1));
                            break;
                        case 'flags':
                            if (preg_match("/ vmx/", $arrBuff1)) {
                                $dev->setVirt("vmx");
                            } elseif (preg_match("/ svm/", $arrBuff1)) {
                                $dev->setVirt("svm");
                            } elseif (preg_match("/ hypervisor/", $arrBuff1)) {
                                $dev->setVirt("hypervisor");
                            }
                            break;
                        case 'i size':
                        case 'd size':
                            if ($dev->getCache() === null) {
                                $dev->setCache($arrBuff1 * 1024);
                            } else {
                                $dev->setCache($dev->getCache() + ($arrBuff1 * 1024));
                            }
                            break;
                        case 'cpu architecture':
                            $arch = $arrBuff1;
                            break;
                        case 'cpu implementer':
                            $impl = $arrBuff1;
                            break;
                        case 'cpu part':
                            $part = $arrBuff1;
                            break;
                        }
                    }
                }
                if ($arch === null) $arch = $_arch;
                if ($impl === null) $impl = $_impl;
                if ($part === null) $part = $_part;


                // sparc64 specific code follows
                // This adds the ability to display the cache that a CPU has
                // Originally made by Sven Blumenstein <bazik@gentoo.org> in 2004
                // Modified by Tom Weustink <freshy98@gmx.net> in 2004
                $sparclist = array('SUNW,UltraSPARC@0,0', 'SUNW,UltraSPARC-II@0,0', 'SUNW,UltraSPARC@1c,0', 'SUNW,UltraSPARC-IIi@1c,0', 'SUNW,UltraSPARC-II@1c,0', 'SUNW,UltraSPARC-IIe@0,0');
                foreach ($sparclist as $name) {
                    if (CommonFunctions::rfts('/proc/openprom/'.$name.'/ecache-size', $buf, 1, 32, false)) {
                        $dev->setCache(base_convert(trim($buf), 16, 10));
                    }
                }
                // sparc64 specific code ends

                // XScale detection code
                if (($arch === "5TE") && ($dev->getBogomips() != null)) {
                    $dev->setCpuSpeed($dev->getBogomips()); //BogoMIPS are not BogoMIPS on this CPU, it's the speed
                    $speedset = true;
                    $dev->setBogomips(null); // no BogoMIPS available, unset previously set BogoMIPS
                }

                if (($dev->getBusSpeed() == 0) && ($_buss !== null)) {
                    $dev->setBusSpeed($_buss);
                }
                if (($dev->getCpuSpeed() == 0) && ($_cpus !== null)) {
                    $dev->setCpuSpeed($_cpus);
                    $speedset = true;
                }

                if ($proc != null) {
                    if (!is_numeric($proc)) {
                        $proc = 0;
                    }
                    // variable speed processors specific code follows
                    if (CommonFunctions::rfts('/sys/devices/system/cpu/cpu'.$proc.'/cpufreq/cpuinfo_cur_freq', $buf, 1, 4096, false)) {
                        $dev->setCpuSpeed(trim($buf) / 1000);
                        $speedset = true;
                    } elseif (CommonFunctions::rfts('/sys/devices/system/cpu/cpu'.$proc.'/cpufreq/scaling_cur_freq', $buf, 1, 4096, false)) {
                        $dev->setCpuSpeed(trim($buf) / 1000);
                        $speedset = true;
                    }
                    if (CommonFunctions::rfts('/sys/devices/system/cpu/cpu'.$proc.'/cpufreq/cpuinfo_max_freq', $buf, 1, 4096, false)) {
                        $dev->setCpuSpeedMax(trim($buf) / 1000);
                    }
                    if (CommonFunctions::rfts('/sys/devices/system/cpu/cpu'.$proc.'/cpufreq/cpuinfo_min_freq', $buf, 1, 4096, false)) {
                        $dev->setCpuSpeedMin(trim($buf) / 1000);
                    }
                    // variable speed processors specific code ends
                    if (PSI_LOAD_BAR) {
                            $dev->setLoad($this->_parseProcStat('cpu'.$proc));
                    }
/*
                    if (CommonFunctions::rfts('/proc/acpi/thermal_zone/THRM/temperature', $buf, 1, 4096, false)
                       &&  preg_match("/(\S+)\sC$/", $buf, $value)) {
                        $dev->setTemp(value[1]);
                    }
*/
                    if (($arch !== null) && ($impl !== null) && ($part !== null)) {
                        if (($impl === '0x41')
                           && (($_hard === 'BCM2708') || ($_hard === 'BCM2835') || ($_hard === 'BCM2709') || ($_hard === 'BCM2836') || ($_hard === 'BCM2710') || ($_hard === 'BCM2837'))
                           && ($_revi !== null)) { // Raspberry Pi detection (instead of 'cat /proc/device-tree/model')
                            if ($raslist === null) $raslist = @parse_ini_file(PSI_APP_ROOT."/data/raspberry.ini", true);
                            if ($raslist && !preg_match('/[^0-9a-f]/', $_revi)) {
                                if (($revidec = hexdec($_revi)) & 0x800000) {
                                    if ($this->sys->getMachine() === '') {
                                        $manufacturer = ($revidec >> 16) & 15;
                                        if (isset($raslist['manufacturer'][$manufacturer])) {
                                            $manuf = ' '.$raslist['manufacturer'][$manufacturer];
                                        } else {
                                            $manuf = '';
                                        }
                                        $model = ($revidec >> 4) & 255;
                                        if (isset($raslist['model'][$model])) {
                                            $this->sys->setMachine('Raspberry Pi '.$raslist['model'][$model].' (PCB 1.'.($revidec & 15).$manuf.')');
                                        } else {
                                            $this->sys->setMachine('Raspberry Pi (PCB 1.'.($revidec & 15).$manuf.')');
                                        }
                                    }
                                } else {
                                    if ($this->sys->getMachine() === '') {
                                        if (isset($raslist['old'][$revidec & 0x7fffff])) {
                                            $this->sys->setMachine('Raspberry Pi '.$raslist['old'][$revidec & 0x7fffff]);
                                        } else {
                                            $this->sys->setMachine('Raspberry Pi');
                                        }
                                    }
                                }
                            }
                        } elseif (($_hard !== null) && ($this->sys->getMachine() === '')) { // other ARM hardware
                            $this->sys->setMachine($_hard);
                        }
                        if ($cpulist === null) $cpulist = @parse_ini_file(PSI_APP_ROOT."/data/cpus.ini", true);
                        if ($cpulist && (isset($cpulist['cpu'][$cpuimplpart = strtolower($impl.','.$part)]))) {
                            if (($cpumodel = $dev->getModel()) !== '') {
                                $dev->setModel($cpumodel.' - '.$cpulist['cpu'][$cpuimplpart]);
                            } else {
                                $dev->setModel($cpulist['cpu'][$cpuimplpart]);
                            }
                        }
                    } elseif (($_hard !== null) && ($this->sys->getMachine() === '')) { // other hardware
                        $this->sys->setMachine($_hard);
                    }

                    if ($dev->getModel() === "") {
                        $dev->setModel("unknown");
                    }
                    $cpucount++;
                    $this->sys->setCpus($dev);
                }
            }
            $cpudevices = glob('/sys/devices/system/cpu/cpu*/uevent', GLOB_NOSORT);
            if (is_array($cpudevices) && (($cpustopped = count($cpudevices)-$cpucount) > 0)) {
                for (; $cpustopped > 0; $cpustopped--) {
                    $dev = new CpuDevice();
                    $dev->setModel("stopped");
                    if ($speedset) {
                        $dev->setCpuSpeed(-1);
                    }
                    $this->sys->setCpus($dev);
                }
            }
        }
    }
401949
def _get_cpu_info_internal():
	'''
	
	'''

	# Get the CPU arch and bits
	arch, bits = _parse_arch(DataSource.arch_string_raw)

	friendly_maxsize = { 2**31-1: '32 bit', 2**63-1: '64 bit' }.get(sys.maxsize) or 'unknown bits'
	friendly_version = "{0}.{1}.{2}.{3}.{4}".format(*sys.version_info)
	PYTHON_VERSION = "{0} ({1})".format(friendly_version, friendly_maxsize)

	info = {
		'python_version' : PYTHON_VERSION,
		'cpuinfo_version' : CPUINFO_VERSION,
		'cpuinfo_version_string' : CPUINFO_VERSION_STRING,
		'arch' : arch,
		'bits' : bits,
		'count' : DataSource.cpu_count,
		'arch_string_raw' : DataSource.arch_string_raw,
	}

	# Try the Windows wmic
	_copy_new_fields(info, _get_cpu_info_from_wmic())

	# Try the Windows registry
	_copy_new_fields(info, _get_cpu_info_from_registry())

	# Try /proc/cpuinfo
	_copy_new_fields(info, _get_cpu_info_from_proc_cpuinfo())

	# Try cpufreq-info
	_copy_new_fields(info, _get_cpu_info_from_cpufreq_info())

	# Try LSCPU
	_copy_new_fields(info, _get_cpu_info_from_lscpu())

	# Try sysctl
	_copy_new_fields(info, _get_cpu_info_from_sysctl())

	# Try kstat
	_copy_new_fields(info, _get_cpu_info_from_kstat())

	# Try dmesg
	_copy_new_fields(info, _get_cpu_info_from_dmesg())

	# Try /var/run/dmesg.boot
	_copy_new_fields(info, _get_cpu_info_from_cat_var_run_dmesg_boot())

	# Try lsprop ibm,pa-features
	_copy_new_fields(info, _get_cpu_info_from_ibm_pa_features())

	# Try sysinfo
	_copy_new_fields(info, _get_cpu_info_from_sysinfo())

	# Try querying the CPU cpuid register
	_copy_new_fields(info, _get_cpu_info_from_cpuid())

	# Try platform.uname
	_copy_new_fields(info, _get_cpu_info_from_platform_uname())

	return info
634609
def __get_cpu(self):
        """"""
        # Never update more than 1 time per cached_time
        if self.timer_cpu.finished():
            self.cpu_percent = psutil.cpu_percent(interval=0.0)
            # Reset timer for cache
            self.timer_cpu = Timer(self.cached_time)
        return self.cpu_percent
733466
def get_field(field, slog, fl=False):
        
        field += r'\:\s+([\d\.]+)'
        match = re.search(field, slog)
        if match:
            if fl:
                return float(match.group(1))
            return int(match.group(1))
        return 0
743423
def _GetHWInfos(client_list, batch_size=10000, token=None):
  """"""

  # This function returns a dict mapping each client_id to a set of reported
  # hardware serial numbers reported by this client.
  hw_infos = {}

  logging.info("%d clients to process.", len(client_list))

  c = 0

  for batch in collection.Batch(client_list, batch_size):
    logging.info("Processing batch: %d-%d", c, c + batch_size)
    c += len(batch)

    client_objs = aff4.FACTORY.MultiOpen(batch, age=aff4.ALL_TIMES, token=token)

    for client in client_objs:
      hwi = client.GetValuesForAttribute(client.Schema.HARDWARE_INFO)

      hw_infos[client.urn] = set(["%s" % x.serial_number for x in hwi])

  return hw_infos
480750
def _get_cpu(self):
        '''
        
        '''
        # CPU data in grains is OK-ish, but lscpu is still better in this case
        out = __salt__['cmd.run_all']("lscpu")
        salt.utils.fsutils._verify_run(out)
        data = dict()
        for descr, value in [elm.split(":", 1) for elm in out['stdout'].split(os.linesep)]:
            data[descr.strip()] = value.strip()

        return data
554930
def get_proc_return_status(self):
        
        if self._session is None:
            return None
        if not self._session.has_status:
            self._session.find_return_status()
        return self._session.ret_status if self._session.has_status else None
583871
def get_cpu_timings(self):
        
        timings = {}
        with open('/proc/stat', 'r') as file_obj:
            for line in file_obj:
                if 'cpu' in line:
                    line = line.strip().split()
                    timings[line[0]] = [int(x) for x in line[1:]]

        return timings