linux下配置自定义的python服务进程

直接上代码

testXXXX.py:

import logging
import logging.handlers
import subprocess
import time


class CliTool:
    def __init__(self):
        pass

    def cmd_sync(self, cmdlist):
        res = subprocess.run(cmdlist, capture_output=True, check=True)
        return res

    def cmd_async_nowait(self, cmd):
        p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        out, err = p.communicate()
        return out, err

    def cmd_async_wait(self, cmd, timeout):
        p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        time_out_flag = False
        for i in range(timeout):
            time.sleep(1)
            if None == p.poll():
                # subprocess is in progress.
                if i + 1 >= timeout:
                    p.kill()
                    time_out_flag = True
                    break
                else:
                    continue
            else:
                break

        if time_out_flag:
            out = []
            err = ['timeout']
        else:
            out, err = p.communicate()

        return out, err


class testXXXX:
    def __init__(self):
        self.logger = logging.getLogger('testXXXX')
        self.configLog()
        self.cli_tool = CliTool()

    def configLog(self):
        self.logger = logging.getLogger('testXXXX')
        self.logger.setLevel(level=logging.INFO)

        # timestamp format same with syslog timestamp format
        formatter = logging.Formatter('%(asctime)s - [%(filename)s:%(lineno)d] - %(message)s', "%b %d %H:%M:%S")

        file_handler = logging.handlers.WatchedFileHandler('/var/log/mylog')
        file_handler.setLevel(level=logging.INFO)
        file_handler.setFormatter(formatter)

        self.logger.addHandler(file_handler)

    def doTest(self):
        while True:

            out, err = self.cli_tool.cmd_async_wait('ping www.baidu.com -c 10', 60)
            outputList = str(out).split('\\n')
            for line in outputList:
                self.logger.info(line)


if __name__ == '__main__':
    testObj = testXXXX()
    testObj.doTest()

testXXXX_config.sh

#!/bin/bash
mv testXXXX.service  /lib/systemd/system/
mv testXXXX.py /usr/bin/
ln -s /lib/systemd/system/testXXXX.service /etc/systemd/system/
systemctl enable /etc/systemd/system/testXXXX.service

test_XXXX.service

[Unit]
Description=test XXXX
After=YYYY.service

[Service]
Type=simple
Restart=always
RestartSec=10
ExecStart=/usr/bin/python3 /usr/bin/test_XXXX.py


[Install]
WantedBy=multi-user.target
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值