LoginSignup
0
0

More than 3 years have passed since last update.

Python の systemd service のファイルIO

Posted at

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()
0
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
0
0