[CENTOS] Note to daemonize python

I want to make something written in python a daemon

I always wanted to run a program written in python on Sakura's VPS. In addition, it is easy because it can be operated with systemctl. The method is the following pakuri. Try to make your own command into a service using Systemd

environment

--Sakura's VPS

How to

program

/opt/python_daemon.py


#!/usr/bin/env python
import time
import os
import sys

def main_unit():#Write the time every 10 seconds
	while True:
		filepath = '/opt/pydmon.log'
		log_file = open(filepath,'a')
		try:
			log_file.write(time.ctime()+"\n")
		finally:
			log_file.close()
			time.sleep(10)

def daemonize():
	pid = os.fork()#Fork the process here
	if pid > 0:#For parent process(pid is the process ID of the child process)
		pid_file = open('/var/run/python_daemon.pid','w')
		pid_file.write(str(pid)+"\n")
		pid_file.close()
		sys.exit()
	if pid == 0:#For child processes
		main_unit()

if __name__ == '__main__':
	while True:
		daemonize()

Let's specify Shebang.

Add #! / Usr / bin / env python or #! / Usr / bin / python to the beginning. #! / usr / bin / env python seems to preferentially use python at the beginning of $ PATH. On the other hand, #! / Usr / bin / python seems to directly specify python under / usr / bin /. Inconvenience may occur if the version is different.

I was familiar with Stack overflow, so if you are interested, please refer to it. Why do people write #!/usr/bin/env python on the first line of a Python script?

About daemonize ()

Forking the process, the parent process writes the child process ID returned in the variable pid to the pid file and disappears. The child process, on the other hand, runs main_unit () every 10 seconds in an infinite loop.

After saving, give execute permission.

sudo chmod 755 /opt/python_daemon.py You should now have execute permission.

Create a unit definition file

/usr/lib/systemd/system/pythondaemon.service


[Unit]
Description=PythonDaemon

[Service]
ExecStart=/opt/python_daemon.py
Restart=always
Type=forking
PIDFile=/var/run/python_daemon.pid

[Install]
WantedBy=multi-user.target

Daemon definition file. If ExecStart and PID File match, I think it's okay to copy and paste.

Start the daemon

sudo systemctl daemon-reload sudo systemctl start pythondaemon.service

After reloading the daemon, the newly created pythondaemon.service will be recognized. Then start it with start.

result

$ sudo systemctl status pythondaemon.service


● pythondaemon.service - PythonDaemon
   Loaded: loaded (/usr/lib/systemd/system/pythondaemon.service; disabled; vendor preset: disabled)
   Active: active (running)since month 2017-09-11 00:35:12 JST; 10s ago
  Process: 4633 ExecStart=/opt/python_daemon.py (code=exited, status=0/SUCCESS)
 Main PID: 4634 (python)
   CGroup: /system.slice/pythondaemon.service
           └─4634 python /opt/python_daemon.py

It moved!

pydmon.log looks like this

$ cat pydmon.log 
Mon Sep 11 00:35:12 2017
Mon Sep 11 00:35:22 2017
Mon Sep 11 00:35:32 2017
Mon Sep 11 00:35:42 2017
Mon Sep 11 00:35:52 2017
Mon Sep 11 00:36:02 2017
Mon Sep 11 00:36:12 2017
Mon Sep 11 00:36:22 2017
Mon Sep 11 00:36:32 2017
Mon Sep 11 00:36:42 2017
Mon Sep 11 00:36:52 2017
Mon Sep 11 00:37:02 2017

Impressions

It was fun and impressed because it can be managed with systemctl

Recommended Posts

Note to daemonize python
Note: Python
Python note
Python study note_002
Note: Python Decorator
Updated to Python 2.7.9
Python programming note
[Python] Learning Note 1
Python study note_004
Python study note_003
[Note] openCV + python
Python beginner's note
"Backport" to python 2
Trying to handle SQLite3 with Python [Note]
3 ways to parse time strings in python [Note]
[Note] future sentence ~ Python ~
[Note] File reading ~ Python ~
How to install Python
Changes from Python 3.0 to Python 3.5
Changes from Python 2 to Python 3.0
Rewrite Python2 code to Python3 (2to3)
How to install python
Introduction to Python language
Daemonize a Python process
Introduction to OpenCV (python)-(2)
Python Note: When assigning a value to a string
Note: python Skeleton Nya
Introducing Python 2.7 to CentOS 6.6
Python basic grammar note (4)
Python basic grammar note (3)
Connect python to mysql
[Python MinMaxScaler] Normalize to 0 ~ 1
Python Tkinter Primer Note
Python script to get note information with REAPER
Note assigning image textures to materials in Maya python
Reading Note: An Introduction to Data Analysis with Python
Things to note when initializing a list in Python
Mercurial stopped working after migrating from Python 2 to Python 3 (Note)
Python Note: The mystery of assigning a variable to a variable
Connect to BigQuery with Python
[2020.8 latest] How to install Python
[python] Convert date to string
Post from Python to Slack
How to install Python [Windows]
Post to vim → Python → Slack
To flush stdout in Python
Convert numpy int64 to python int
python3: How to use bottle (2)
[Python] Convert list to Pandas [Pandas]
Cheating from PHP to Python
A road to intermediate Python
Try to understand Python self
Python notes to forget soon
[Python] How to use list 1
Connect to Wikipedia with Python
How to update Python Tkinter to 8.6
Post to slack with Python 3
Anaconda updated from 4.2.0 to 4.3.0 (python3.5 updated to python3.6)
Python Input Note in AtCoder
[Note] Operate MongoDB with Python
Post to Twitter using Python