简体   繁体   English

python脚本休眠时服务停止

[英]service stops when python script sleeps

I wanted to create a Service that runs a python script. 我想创建一个运行python脚本的服务。 This is what i have so far: 这是我到目前为止所拥有的:

  • The Service 服务
[Unit]
Description=A test unit

[Service]
ExecStart=/usr/bin/python3 /home/telnet/projects/test.py
Restart=on-abort
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=test
  • The .py file .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)

Doing py test.py works, and the f file gets filled with the Strings. 进行py test.py工作,并且f文件充满了字符串。

But when running the script from a service, I get this: 但是从服务运行脚本时,我得到了:

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

But the f file is empty. 但是f文件为空。 It doesn't write anything on it. 它没有写任何东西。

you need to close the file try this: 您需要关闭文件,请尝试以下操作:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM