служба останавливается, когда скрипт Python спит - PullRequest
1 голос
/ 02 апреля 2019

Я хотел создать Сервис, который запускает скрипт на Python. Это то, что у меня есть:

  • Служба
[Unit]
Description=A test unit

[Service]
ExecStart=/usr/bin/python3 /home/telnet/projects/test.py
Restart=on-abort
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=test
  • Файл .py
import os
import time

i = 0
log = str(os.path.dirname(os.path.abspath(__file__))) + \
      '/logs/test_service_log.txt'

f = open(log, 'w')


def write():
        global i, log
        named_tuple = time.localtime()
        string_time = time.strftime('%d/%m/%Y, %H:%M:%S', named_tuple)
        f.write(str(i) + '\t' + string_time + '\thello' + '\tbye' + '\n')
        i = i+1


while True:
        write()
        time.sleep(1)

Выполнение py test.py работает, а файл f заполняется строками.

Но при запуске сценария из службы я получаю следующее:

test.service - A test unit
   Loaded: loaded (/etc/systemd/system/test.service; static; vendor preset: enab
   Active: active (running) since Wed 2017-04-12 02:33:57 CEST; 4s ago
 Main PID: 1546 (python3)
    Tasks: 1 (limit: 512)
   Memory: 3.1M
      CPU: 113ms
   CGroup: /system.slice/test.service
           └─1546 /usr/bin/python3 /home/telnet/projects/test.py

Но файл f пуст. На нем ничего не написано.

1 Ответ

0 голосов
/ 02 апреля 2019

вам нужно закрыть файл попробуйте это:

import time

cwd = '/home/telnet/projects/'

i = 0
#make the file
f = open(cwd + 'logs/test_service_log.txt', 'w+')
#close it
f.close()
def write():
        global i
        named_tuple = time.localtime()
        string_time = time.strftime("%d/%m/%Y, %H:%M:%S", named_tuple)
        f.write(str(i) + '\t' + string_time + '\thello'  + '\tbye' + '\n')
        i = i+1

while True:
        #open it in append mode
        f = open(cwd + 'logs/test_service_log.txt', 'a')
        write()
        #close it to save it
        f.close()
        time.sleep(1)
...