LoginSignup
2
0

会社あるある。打刻ミスの証跡を集めてくれるpython

Posted at

私の会社では、勤怠管理としてカードをかざすことがある。そして、会社としてはPCのロガーも管理対象としているため、勤怠打刻とPCの電源管理をすることで、労働時間の乖離がないようにしている。

そこで、ミスった時やPCのロガーが取れない時に、ちゃちゃっと取れるようにpythonを書いてみた

簡単に要件

  • 言語:python
  • 機体:macbook
  • データをCSVに出力する
  • temirnalの "last" コマンドで取得する

前提

  • kintai.csvとpythonを同じ配下
    • これは勝手にパスを変えればOK
  • lastコマンド打てば正直いいので、意味あるかどうかは知らん笑
  • csvじゃなくて、jsonでもできるよ

書いてみたコード

CSVで出力するようにする

csvで出力
import subprocess
import csv

# terminalでlastコマンドを実行
process = subprocess.Popen(['last'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

output, error = process.communicate()
if error:
    print("Error:", error)

# 出力を行単位で分割
lines = output.strip().split('\n')

# CSVファイルに保存
csv_filename = './kintai.csv'
with open(csv_filename, 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    # ヘッダー
    writer.writerow(['User', 'TTY', 'Login@', 'Logout', 'Duration'])
    
    # 各行を解析してCSVに書き込み
    for line in lines:
        writer.writerow(line.split())

csv_filename

結果

Screenshot 2023-12-16 at 9.54.57.png

ちなみに、vscodeでrainbow csvを使ったので、こんなになってます。

JSONで出力するようにする

jsonで出力
import subprocess
import json

# 'last' コマンドを実行
process = subprocess.Popen(['last'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

output, error = process.communicate()
if error:
    print("Error:", error)

# 出力を行単位に分割
lines = output.strip().split('\n')

# JSON形式で保存するためのリストを作成
json_data = []
headers = ['User', 'TTY', 'Login@', 'Logout', 'Duration']

for line in lines:
    # 各行をスペースで分割して辞書に変換
    parts = line.split()
    if len(parts) < len(headers):  # 不完全な行は無視
        continue
    record = dict(zip(headers, parts))
    json_data.append(record)

# JSONファイルに保存
json_filename = './kintai.json'
with open(json_filename, 'w') as jsonfile:
    json.dump(json_data, jsonfile, indent=4)

json_filename

結果

Screenshot 2023-12-16 at 10.02.49.png
つづく

最後に

ここまではそんなに意味はないんですが、これ以降にいろいろ構築してAPI化までしたら勤怠でちょっと楽々なものを作れました😃(人事には秘密🎶)

2
0
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
2
0