【问题标题】:service stops when python script sleeps当 python 脚本休眠时服务停止
【发布时间】:2019-08-23 18:00:51
【问题描述】:

我想创建一个运行 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 文件是空的。它没有写任何东西。

【问题讨论】:

    标签: python time service sleep


    【解决方案1】:

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

    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)
    

    【讨论】:

    • with不是自动关闭文件了吗?无论如何,为什么使用 py 运行脚本而不是作为服务运行?
    • "with 语句通过封装常见的准备和清理任务来简化异常处理。"此外,它会自动关闭文件。 with 语句提供了一种确保始终使用清理的方法。
    猜你喜欢
    • 2018-11-20
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 2012-08-23
    • 2020-12-21
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多