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
#!/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()
#! / Usr / bin / env python or
#! / Usr / bin / python to the beginning.
#! / usr / bin / env python seems to preferentially use python at the beginning of
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?
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.
sudo chmod 755 /opt/python_daemon.py
You should now have execute permission.
[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.
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
$ 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
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
It was fun and impressed because it can be managed with