欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

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

时间:2023-07-23

直接上代码

testXXXX.py:

import loggingimport logging.handlersimport subprocessimport timeclass 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, errclass 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/bashmv 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 XXXXAfter=YYYY.service[Service]Type=simpleRestart=alwaysRestartSec=10ExecStart=/usr/bin/python3 /usr/bin/test_XXXX.py[Install]WantedBy=multi-user.target

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。