2019年5月2日木曜日

systemd に Python スクリプトをサービスとして登録

systemd に Python スクリプトをサービスとして登録する方法が https://qiita.com/DQNEO/items/0b5d0bc5d3cf407cb7ff にあったのでやってみました。

環境

  • Raspberry Pi 3 model B
  • Raspbian GNU/Linux 9.4 (stretch)

サービスとして登録する Python スクリプト用意

L チカする Python スクリプトです。

$ cat /some/where/test.py
#!/usr/bin/env python3

import RPi.GPIO as GPIO
import time

GPIO_LED = 21

GPIO.setmode(GPIO.BCM)
GPIO.setup(GPIO_LED, GPIO.OUT)

while True:
    GPIO.output(GPIO_LED, GPIO.HIGH)
    time.sleep(1)

    GPIO.output(GPIO_LED, GPIO.LOW)
    time.sleep(0.1)

実行権付与しました。

$ sudo chmod +x /some/where/test.py

Unit定義ファイル作成

$ cat /etc/systemd/system/test.service
[Unit]
Description = test daemon

[Service]
ExecStart = /some/where/test.py
Restart = always
Type = simple

[Install]
WantedBy = multi-user.target

サービスとして認識されたか確認

$ sudo systemctl list-unit-files --type=service | grep ^test
test.service                           disabled

自動起動 On

$ sudo systemctl enable test
Created symlink /etc/systemd/system/multi-user.target.wants/test.service → /etc/systemd/system/test.service.

こんな感じでシンボリックリンクがはられました。

$ ls -la /etc/systemd/system/multi-user.target.wants/test.service
lrwxrwxrwx 1 root root 32 May  2 23:31 /etc/systemd/system/multi-user.target.wants/test.service -> /etc/systemd/system/test.service

起動しました。L チカもしました。

$ sudo systemctl start test

ステータス確認しました。

$ sudo systemctl status test
● test.service - test daemon
   Loaded: loaded (/etc/systemd/system/test.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2019-05-02 23:37:07 JST; 1min 42s ago
 Main PID: 15408 (python3)
   CGroup: /system.slice/test.service
           └─15408 python3 /some/where/test.py

May 02 23:37:07 raspberrypi systemd[1]: Started test daemon.

Raspbian を再起動すると test スクリプトも自動起動されました。

Python で OctoPrint で Marlin でステッピングモーター開放

#!/usr/bin/env python3

import urllib.request
import json

url = 'http://octoprint:5000/api/printer/command'
json_data = json.dumps(
    {
        'command': 'M18 X Y Z',
    }
).encode("utf-8")

with open('api-key') as f:
    api_key = f.read().rstrip()

req = urllib.request.Request(url)
req.add_header('X-Api-Key', api_key)
req.add_header('Content-Type', 'application/json')
req.data = json_data

with urllib.request.urlopen(req) as f:
    print(f.read().decode())