pure Pythonのライブラリapcaccessを使って、apcupsdのデータを取得する

apcupsdで取得できるUPS情報をPythonのオブジェクトとして扱う方法を探したところ、apcaccessライブラリを見つけました。

 
試してみた時のメモを残します。

 

環境

  • Windows10 x64
  • Python 3.5.1 32bit
  • apcaccess 0.0.4

 

実装

PyPIGitHubにはドキュメントがないため、テストコードやソースコードを見たところ、

  • apcaccess.status.get()で、UPSの情報を取得
    • 引数hostIPアドレスなどを与えれば、リモートのapcupsdの情報も取得可能
  • apcaccess.status.parse()で、PythonのOrderedDictへ変換
  • apcaccess.status.print_status()で、読みやすい形でprintする

ということが分かりました。

 
usage_apcaccess.py

from apcaccess.status import get, print_status, parse

def main(host="localhost"):
    # apcupsdよりデータ取得
    raw = get(host=host)
    # rawデータだと文字化け
    print(raw)
    print("-"*10)

    # OrderedDictへparse
    parsed = parse(raw)
    print(parsed)

    # 読みやすい形でprint
    print_status(raw)
    print("-"*10)

if __name__ == "__main__":
    # ローカルホスト
    # main()
    
    # リモートホスト
    main(host="192.168.0.10")

 
結果

>python usage_apcaccess.py

# print(raw)
 APC      : xxx,xxx,xxxx
 'DATE     : 2016-06-29 
 HOSTNAME : your host
 )VERSION  : 3.14.12 (29 March 2014) Win32
 UPSNAME  : UPS_IDEN
 CABLE    : Custom Cable Smart
 DRIVER   : APC Smart UPS (any)
 UPSMODE  : Stand Alone
...

# print(parse(raw))
OrderedDict([('APC', 'xxx,xxx,xxxx'), ('DATE', '2016-06-29'), ('HOSTNAME', 'your host'), ('VERSION', '3.14.12 (29 March 2014) Win32'), ('UPSNAME', 'UPS_IDEN'), ('CABLE', 'Custom Cable Smart'), ('DRIVER', 'APC Smart UPS (any)'), ('UPSMODE', 'Stand Alone'), ...])

# print_status(raw)
APC      : xxx,xxx,xxxx
DATE     : 2016-06-29
HOSTNAME : your host
VERSION  : 3.14.12 (29 March 2014) Win32
UPSNAME  : UPS_IDEN
CABLE    : Custom Cable Smart
DRIVER   : APC Smart UPS (any)
UPSMODE  : Stand Alone

 
なかなか良さそうです。

 

ソースコード

GitHubに上げました。usage_apcaccess.pyが今回のスクリプトファイルです。
thinkAmi-sandbox/apcupsd_python-sample