2022年9月21日 星期三

How to Setup Python Script Autorun As a Service in Ubuntu 20.04 (2022)

 https://websofttechs.com/tutorials/how-to-setup-python-script-autorun-in-ubuntu-18-04/

 

Dummy Python Program


https://www.digitalocean.com/community/questions/trying-to-change-workingdirectory-of-systemd-service-unit

[Service]

WorkingDirectory=/home/pi

 

 

nano /home/ricky/apply.py

#!/usr/bin/python3
import time, datetime, os
from pathlib import Path
Path("./logs/").mkdir(parents=True, exist_ok=True)
filename: str = datetime.datetime.now().strftime(f"./logs/%Y%m%d.%H%M%S.pid.{os.getpid()}.log")
while True:
    line: str = str(datetime.datetime.now())
    print(line)
    with open(filename, "a") as outfile:
        outfile.write(line+'\n')
    time.sleep(2)

sudo nano /lib/systemd/system/apple.service

[Unit]
Description=Apple Service
After=multi-user.target
Conflicts=getty@tty1.service

[Service]
Type=simple
WorkingDirectory=/home/ricky/
ExecStart=/usr/bin/python3 /home/ricky/apple.py
StandardInput=tty-force

[Install]
WantedBy=multi-user.target


sudo systemctl daemon-reload

sudo systemctl enable apple
sudo systemctl start apple

sudo systemctl status apple

sudo systemctl restart apple

sudo systemctl stop apple
sudo systemctl disable apple


Dummy Python Program to python -m with venv

service
=======

sudo nano /lib/systemd/system/my_app.service

[Unit]

Description=MyApp  

After=multi-user.target

Conflicts=getty@tty1.service

[Service]

Type=simple

WorkingDirectory=/home/ricky/my_app

ExecStart=/home/ricky/my_app/venv/bin/python3 -m my_app --cfg /home/ricky/my_app/quant-server.yml

StandardInput=tty-force

[Install]

WantedBy=multi-user.target


systemctl
=========

sudo systemctl daemon-reload
sudo systemctl enable my_app
sudo systemctl start my_app
sudo systemctl status my_app
sudo systemctl restart my_app
sudo systemctl stop my_app
sudo systemctl disable my_app


沒有留言:

張貼留言

2023 Promox on Morefine N6000 16GB 512GB

2023 Promox on Morefine N6000 16GB 512GB Software Etcher 100MB (not but can be rufus-4.3.exe 1.4MB) Proxmox VE 7.4 ISO Installer (1st ISO re...