Posted at

Python の systemd service のファイルIO

Raspbian 上で動く Systemd Service を Python でログを取りたいときのメモ.

Raspbian に限った話ではないかもしれない.


.service ファイル


logwrite.service

[Unit]

Description = Log write test

[Service]
ExecStart = path/to/main.py

[Install]
WantedBy = multi-user.target



ファイルに書いてくれないコード

※ Systemd Service として実行しなければ(python3 main.py などとすれば)このコードでも書き込める.


main.py

#!/usr/bin/python3


from writer import LogWriter

if __name__ == '__main__':
writer = LogWriter('path/to/logfile')
writer.write('foo')
writer.write('bar')
writer.write('baz')
writer.close()



writer.py

import csv

import time

TIME_FORMAT = '%y/%m/%d;%H:%M:%S'

class LogWriter:
def __init__(self, path):
self.logfile = open(path, 'a')
self.writer = csv.writer(self.logfile, lineterminator='\n')

def write(self, data):
self.writer.writerow([time.strftime(TIME_FORMAT), data])

def close(self):
self.logfile.close()



ファイルに書いてくれるコード

main.pyopen した.


main.py

#!/usr/bin/python3


from writer import LogWriter

if __name__ == '__main__':
logfile = open('path/to/logfile', 'a')
writer = LogWriter(logfile)
writer.write('foo')
writer.write('bar')
writer.write('baz')
writer.close()



writer.py

import csv

import time

TIME_FORMAT = '%y/%m/%d;%H:%M:%S'

class LogWriter:
def __init__(self, logfile):
self.logfile = logfile
self.writer = csv.writer(logfile, lineterminator='\n')

def write(self, data):
self.writer.writerow([time.strftime(TIME_FORMAT), data])

def close(self):
self.logfile.close()