python - Linux (Ubuntu) 中的 systemd 服务出错

标签 python linux ubuntu systemd

我尝试在 Ubuntu 中创建服务,但出现错误。

我写了下面的代码-

FileSystemWatcher.py

import requests
import json
import logging
import sys
import os
import datetime
from watchdog.events import PatternMatchingEventHandler


class DirectoryChangedHandler(PatternMatchingEventHandler):

    patterns = ["*.json","*.csv"]

    logFileName = datetime.datetime.now().strftime('%Y%m%d_log.log')
    script_dir = os.path.dirname(__file__)  # <-- absolute dir the script is in
    rel_path = "log/"+logFileName
    abs_logfile_path = os.path.join(script_dir, rel_path)

    appConfigFilePath = os.path.abspath('config/app_config.json')
    with open(appConfigFilePath) as data_file:
        config = json.load(data_file)
    logging.basicConfig(filename=abs_logfile_path, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.NOTSET)

    def process(self, event):

        print event.src_path, event.event_type
        try:

            filelist = [('files', open(event.src_path, 'rb'))]
            postUrl = self.config["apiBaseUrl"].encode('utf-8')+self.config["fileUplaodApiUrl"].encode('utf-8')
            uploadResponse = requests.post(postUrl, files=filelist)
            if uploadResponse.status_code == 200:
                print "Upload Successful - ", event.src_path
            else:
                print "Upload Failed - ", event.src_path
        except:
            print "Unexpected error:", sys.exc_info()[0]
            pass

    def on_modified(self, event):
        self.process(event)

    def on_created(self, event):
        self.process(event)

workflow.py-

#!/usr/bin/python2.7

import sys
import time
from watchdog.observers import Observer

import FileSystemWatcher as fSystemWatcher


if __name__ == '__main__':
    args = sys.argv[1:]
    observer = Observer()
    observer.schedule(fSystemWatcher.DirectoryChangedHandler(), path=args[0] if args else '.', recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()

(/lib/systemd/system/FileWatcherSystemd.service)

[Unit]
Description=FileChangeService

[Service]
Type=forking
WorkingDirectory= /home/ashish/Documents/FileSystemWatcher
ExecStart= /home/ashish/Documents/FileSystemWatcher/workflow.py
Restart=on-failure

[Install]
WantedBy=multi-user.target

但我收到以下错误 -

FileWatcherSystemd.service - FileChangeService Loaded: loaded (/lib/systemd/system/FileWatcherSystemd.service; enabled; vendor preset: enabled) Active: inactive (dead) (Result: exit-code) since Wed 2017-07-19 10:44:39 IST; 8min ago Process: 6552 ExecStart=/home/ashish/Documents/FileSystemWatcher/FileSystemWatcher.py (code=exited, status=203/EXEC) Main PID: 6552 (code=exited, status=203/EXEC)

Jul 19 10:44:39 Ashish-PC systemd[1]: FileWatcherSystemd.service: Unit entered failed state. Jul 19 10:44:39 Ashish-PC systemd[1]: FileWatcherSystemd.service: Failed with result 'exit-code'. Jul 19 10:44:39 Ashish-PC systemd[1]: FileWatcherSystemd.service: Service hold-off time over, scheduling restart. Jul 19 10:44:39 Ashish-PC systemd[1]: Stopped FileChangeService. Jul 19 10:44:39 Ashish-PC systemd[1]: FileWatcherSystemd.service: Start request repeated too quickly. Jul 19 10:44:39 Ashish-PC systemd[1]: Failed to start FileChangeService.

我不知道我在 FileSytemWatcher.pyFileWatcherSystemd.service 中做错了什么

最佳答案

尝试将您的服务类型更改为简单。所以

type=simple

您的脚本似乎没有 fork 和退出。如果您的服务类型是 fork ,systemd 会假设已启动的进程 fork ,让某些内容在后台运行并退出。它会等到您的脚本运行完毕。

您的脚本不会退出,systemd 会检测到这一点并给出超时错误。您的脚本似乎处于无限循环等待键盘中断。这种脚本可以“简单”地运行。这意味着 systemd 只是在后台启动脚本并继续执行启动序列,而无需等待任何事情。

关于python - Linux (Ubuntu) 中的 systemd 服务出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45182651/

相关文章:

python - Scrapy:使用特定的 python 版本

python - 在嵌套的 For 循环中查找元素

linux - 我想将两个 csv 文件粘贴到一个新文件中

python - 使用 cmake 构建 Opencv 给出涉及 c++11 的错误

bash - 命令行批量重命名

linux - 在 Linux 中删除文件名的 10 个字符

python - python中的排序函数

python - 请让我知道以下python代码中的问题

linux - 没有桌面的 Linux 上的全屏应用程序

c - 打开SSL : What does RSA n e d p q parameters represent?