2020年6月11日木曜日

Systemdを使用して起動時にpythonスクリプトを起動する

目的

起動時にPythonスクリプトを実行させる

Systemdの設定

cat /etc/systemd/system/sample.service

[Unit]
Description=Run Python Script

[Service]
ExecStart=/usr/bin/python3 /home/pi/Desktop/Python/sample.py
WorkingDirectory=/home/pi/Desktop/Python/
User=pi
Group=pi

[Install]
WantedBy=multi-user.target

WorkingDirectoryを設定しておけば、そのフォルダが実行時のカレントディレクトリとなる

サービスの自動起動登録

sudo systemctl enable sample.service

サービスの起動

sudo systemctl restart stocknews.service

もしも下記のエラーが出たら、systemctl daemon-reloadとする

Warning: The unit file, source configuration file or drop-ins of sample.service changed on disk. Run 'systemctl daemon-reload' to reload units

期待通りの働きをしないとき

ログが出るので確認をする

systemctl status sample.service