LoginSignup
25
27

More than 5 years have passed since last update.

RaspberryPiのCPU情報をPythonで取得する

Last updated at Posted at 2016-08-12

#開発環境

HD RaspberryPi B+
OS Raspbian GNU/Linux 8.0 (jessie)
Python ver 2.7.9

動機

RaspberyPi にはvcgencmd commandsという、RaspberyPiの内部情報を取得してくれる簡単なコマンドがあります。

RPI vcgencmd usage

RPI vcgencmd commands Means
vcgencmd measure_temp CPU温度
vcgencmd measure_clock arm PythonCPU周波数
vcgencmd measure_voltsp 電圧取得
vcgencmd get_mem arm CPU(arm)メモリ使用量
vcgencmd get_mem gpu GPU(gpu)メモリ使用量

以前はこれをshellで書いていたのですが、Pythonの方が後々のグラフ作図と相性がいいので、Pythonで外部コマンドを実行できるように書いてしまおうと、言う感じで始めました。

ソースコード

#!/usr/bin/env python$
#coding:utf-8$

#ライブラリをインポートしてくる。$
import os
import commands

#Raspbianの制御コマンド(vcgencmd)を実行$

#温度を取得するRPiコマンド
temp = commands.getoutput("vcgencmd measure_temp").split('=')
print temp[1]

#CPU周波数を取得
clock=commands.getoutput("vcgencmd measure_clock arm").split('=')
print clock[1]

#電圧を取得
volt=commands.getoutput("vcgencmd measure_volts").split('=')
print volt[1]

#CPU(arm),GPUのメモリ使用量
arm=commands.getoutput("vcgencmd get_mem arm").split('=')
print arm[1]

gpu=commands.getoutput("vcgencmd get_mem gpu").split('=')
print gpu[1]

実行結果

38.5'C
700000000
1.2000V
448M
64M

ソースコード解説

外部コマンドをPythonから実行するのが**getoutput()**です。getoutput()は、コマンドを実行した結果のみを返します。getoutput()を使用する場合はcommandsモジュールをimportしてきて下さい。

import commands
commands.getoutput('ls')

**str.split(sep)**はsepを区切り文字として、単語を分割してリストにするメソッドです。区切り文字が指定されない場合は、スペース、タブ、改行文字列で分割される特殊なルールになる事があります。
今回の場合は=で区切っています。理由はsplitを使わないで実行すると

temp = commands.getoutput("vcgencmd measure_temp")
print temp

実行結果

temp=37.9'C

今回、グラフで使用する場合、使いたいのは数値だけなのでtempは余計です。
split('=')で文字を区切ります。

temp = commands.getoutput("vcgencmd measure_temp").split('=')
print temp

実行結果

['temp', "38.5'C"]

この様にリストとして区別してくれるので、後は添字を指定して数値部分だけ、抜き出して表示します。尚、この時区切られた後の値はstr型なので数値として扱う場合は**int()**で文字列を数値に変換して下さい。

temp = commands.getoutput("vcgencmd measure_temp").split('=')
temp_i = int(temp[1])

参考資料

RaspberryPi(Raspbian)のCPUの温度をcatを使わないで取得してみた
pythonで外部のシェルスクリプトやコマンドを実行する方法
文字列の分割・結合 split, join,rsplit

25
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
27