python脚本休眠时服务停止

2024-03-29 00:21:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个运行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文件是空的。上面什么也没写


Tags: 文件pytest脚本loghomebintime
1条回答
网友
1楼 · 发布于 2024-03-29 00:21:07

你需要关闭文件 试试这个:

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)

相关问题 更多 >