Make a Python program a daemon and run it automatically when the OS starts

Until recently, I used to daemonize a slackbot program written in Python with python-daemon, but it was troublesome to manage because the program was not automatically executed when the OS started. When I tried using systemd instead of python-daemon, I was able to execute the program automatically when the OS started, so I will show you how to do it.

Execution environment

Windows 10 Home Python 3.7.3 Raspberry Pi OS 10

1. Program example for running slackbot

run.py


import time

from slackbot.bot import Bot
from slacker import Slacker

def main():
    bot = Bot()
    bot.run()

slack = Slacker('Enter API token')
channel_name = 'Enter the name of the channel you want to post a message to'
message = 'Enter the content of the message'

if __name__ =="__main__":
    slack.chat.post_message(channel_name, message, as_user=True) #Post a message at startup
    time.sleep(3) # 'Start request repeated too quickly.'Measures for
    main() #Launch slackbot

slackbot_settings.py


API_TOKEN = 'Enter API token'
DEFAULT_REPLY = 'Enter the message that the bot returns when you don't understand the meaning of the message addressed to the bot'

PLUGINS = ['run.py, slackbot_settings.Program name used other than py
           (Example: slackbot_module)write']

slackbot_module.py


import random
import re

from slackbot.bot import listen_to

morning_greetings = ['Good morning!', 'Nem ...(˘ω˘)']
@listen_to(r'^(good morning|Good morning ~|Good morning)(There is.*)?$')
def morning_greeting(message, fir_word, sec_word):
    message.reply(random.choice(morning_greetings))
    message.react('Enter the English name of the emoji')

afternoon_greetings = ['Hello!', 'Hello']
@listen_to(r'^Hello.*$')
def afternoon_greeting(message):
    message.reply(random.choice(afternoon_greetings))
    message.react('Enter the English name of the emoji')

night_greetings = ['Good evening!', 'Good evening']
@listen_to(r'^Good evening.*$')
def night_greeting(message):
    message.reply(random.choice(night_greetings))
    message.react('Enter the English name of the emoji)')

important point

Be sure to name the file that describes API_TOKEN slackbot_settings.py: 3 Be sure to write time.sleep (3) in run.py ...! The reason will be explained later.

2. File transfer

Transfer the locally created file to the Raspberry Pi. As a security measure, let's set up public key authentication. After setting, start the command prompt or PowerShell and

scp path of file to copy-i Private key file path-p port number username@hostname:Directory name to put the file

Transfer the file with.

3. SSH connection

Ssh connect to the Raspberry Pi from the command line.

ssh -i Private key file path-p port number username@hostname

You can quickly connect to the remote by creating a configuration file called config directly under~ / .ssh /.

Entry example


Host raspi
    User hoge
    HostName raspberrypi
    Port 2222
    IdentityFile ~/.ssh/id_rsa
    IdentitiesOnly yes

In this example

ssh -i ~/.shh/id_rsa -p 2222 hoge@raspberry

Others,

ssh raspi

You can also make an SSH connection with the command.

4. systemd settings

Create a service file under / etc / systemd / system /. This time I want to daemonize run.py, so I will create a file called rund.service (it doesn't matter if the file name is appropriate).

$ sudo nano /etc/systemd/system/rund.service

Write the following settings to rund.service.

rund.service


[Unit]
Description = slackbot daemon

[Service]
Type = simple
Restart = on-failure
ExecStart =Absolute path to Python3 run.Absolute path to py

[Install]
WantedBy = multi-user.target

Since the writing is finished, I will start systemd.

$ sudo systemctl start rund

Don't forget to check if it works! Let's check the status with the following command.

$ sudo systemctl status rund

If ʻActive: active (running)` is displayed, it is OK.

Set the program called run.py, which was daemonized earlier, to be automatically executed when the OS starts.

$ sudo systemctl enable rund

5. Confirmation of automatic startup

Just in case, make sure that it can be started automatically.

$ sudo reboot

After reconnecting, check the status again with the following command.

$ sudo systemctl status rund

As before, if ʻActive: active (running)` is displayed, the setting is complete! !!

If autostart fails and says'Start request repeated too quickly.'

スクリーンショット 2020-08-16 160625.png

Immediately after starting the OS, the internet connection is not established yet, so even if run.py is executed at that timing, it seems that slackbot fails to start (in my environment, ʻAfter = network.target in the service file). I couldn't even add `). If it fails to start, rund.service will run run.py again. However, because the internet connection is not connected, the startup fails again ... and so on. After investigating, it seems that the automatic start is set to stop if the automatic start fails 5 times and the total time to start run.py for the 6th time is within 10 seconds. As a countermeasure, write time.sleep () in the line before main () so that automatic startup will not be performed 6 times within 10 seconds.


abridgement

if __name__ =="__main__":
    time.sleep(3)
    main()

If you write it like this, it will start automatically.

Recommended Posts

Make a Python program a daemon and run it automatically when the OS starts
Let's write a Python program and run it
2. Make a decision tree from 0 with Python and understand it (2. Python program basics)
Associate Python Enum with a function and make it Callable
Get the matched string with a regular expression and reuse it when replacing on Python3
Check the argument type annotation when executing a function in Python and make an error
[Python] Make the function a lambda function
When writing a program in Python
Finally ... Make a radio control using python on Raspberry Pi 3! (When the magnet is brought closer, the motor moves and stops automatically)
[Python / Jupyter] Translate the comment of the program copied to the clipboard and insert it in a new cell
When I tried to run Python, it was skipped to the Microsoft Store
I tried to make a system to automatically acquire the program guide → register it in the calendar in one day
Run the Python interpreter in a script
[Personal memo] Get data on the Web and make it a DataFrame
A python program that resizes a video and turns it into an image
Make a decision tree from 0 with Python and understand it (4. Data structure)
[Python] A program that rounds the score
I made a system that automatically decides whether to run tomorrow with Python and adds it to Google Calendar.
Make a thermometer with Raspberry Pi and make it visible on the browser Part 3
[Python] Precautions when retrieving data by scraping and putting it in the list
[Python] A program that finds the minimum and maximum values without using methods
[Python] A program that calculates the number of updates of the highest and lowest records
Get the stock price of a Japanese company with Python and make a graph
Use python on Raspberry Pi 3 and turn on the LED when it gets dark!
Periodically run a python program on AWS Lambda
ffmpeg-Build a python environment and split the video
Make a copy of the list in Python
A discussion of the strengths and weaknesses of Python
[Python3] Take a screenshot of a web page on the server and crop it further
The result of making a map album of Italy honeymoon in Python and sharing it
[CGI] Run the Python program on the server with Vue.js + axios and get the output data
[Selenium] Open the link in a new tab and move it [Python / Chrome Driver]
There is a pattern that the program did not stop when using Python threading
Until you can install blender and run it with python for the time being
Until you create a machine learning environment with Python on Windows 7 and run it
A note that runs an external program in Python and parses the resulting line
[Python] A program that counts the number of valleys
Specify the volume on linux and make a sound
Let's make a Makefile and build it (super beginner)
Let's make a simple game with Python 3 and iPhone
Make a breakpoint on the c layer with python
Specifies the function to execute when the python program ends
[Python] Make sure the received function is a user-defined function
[Python] A program that compares the positions of kangaroos.
When accessing a URL containing Japanese (Japanese URL) with python3, it will be encoded in html without permission and an error will occur, so make a note of the workaround.
Run the program without building a Python environment! !! (How to get started with Google Colaboratory)
A story that makes it easy to estimate the living area using Elasticsearch and Python
A program that automatically resizes the iOS app icon to the required image size in Python
How to start the PC at a fixed time every morning and execute the python program
Recursively get the Excel list in a specific folder with python and write it to Excel.
Extract only the sound of a specific instrument from a MIDI file and make it a separate file
Parse the Researchmap API in Python and automatically create a Word file for the achievement list
[Python beginner] Variables and scope inside the function (when the processing inside the function is reflected outside the function and when it is not reflected)
An easy way to view the time taken in Python and a smarter way to improve it
Precautions when inputting from CSV with Python and outputting to json to make it an exe
[Python] A program to find the number of apples and oranges that can be harvested
Note: When Python is run on ImageJ Fiji, java.lang.IllegalArgumentException appears and its solution (mac OS)
Try to make it using GUI and PyQt in Python
Temporarily save a Python object and reuse it in another Python
How to run a Python program from within a shell script
Write a python program to find the editing distance [python] [Levenshtein distance]