BW3-Core/boswatch/processManager.py

101 lines
3.2 KiB
Python
Raw Normal View History

2019-03-04 19:43:32 +01:00
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""!
____ ____ ______ __ __ __ _____
/ __ )/ __ \/ ___/ | / /___ _/ /______/ /_ |__ /
/ __ / / / /\__ \| | /| / / __ `/ __/ ___/ __ \ /_ <
/ /_/ / /_/ /___/ /| |/ |/ / /_/ / /_/ /__/ / / / ___/ /
/_____/\____//____/ |__/|__/\__,_/\__/\___/_/ /_/ /____/
German BOS Information Script
by Bastian Schroll
@file: processManager.py
@date: 04.03.2018
@author: Bastian Schroll
@description: Class for managing sub processes
"""
import logging
import subprocess
logging.debug("- %s loaded", __name__)
class ProcessManager:
2019-03-05 07:49:15 +01:00
def __init__(self, process, textMode=False):
2019-03-05 08:24:55 +01:00
logging.debug("create process instance %s - textMode: %s", process, textMode)
2019-03-04 19:43:32 +01:00
self._args = []
self._args.append(process)
self._stdin = None
self._stdout = subprocess.PIPE
2019-03-05 07:49:15 +01:00
self._stderr = subprocess.STDOUT
2019-03-04 19:43:32 +01:00
self._processHandle = None
2019-03-05 07:49:15 +01:00
self._textMode = textMode
2019-03-05 08:24:55 +01:00
def __del__(self):
self.stop()
2019-03-04 19:43:32 +01:00
def addArgument(self, arg):
2019-03-05 08:24:55 +01:00
logging.debug("add argument to process: %s -> %s", self._args[0], arg)
2019-03-04 19:43:32 +01:00
self._args.append(arg)
def clearArguments(self):
self._args = []
2019-03-05 08:24:55 +01:00
def start(self):
logging.debug("start new process: %s", self._args[0])
2019-03-04 19:43:32 +01:00
self._processHandle = subprocess.Popen(self._args,
stdin=self._stdin,
stdout=self._stdout,
stderr=self._stderr,
2019-03-05 07:49:15 +01:00
universal_newlines=self._textMode)
def stop(self):
if self._processHandle and self.isRunning:
2019-03-05 08:24:55 +01:00
logging.debug("stopping process: %s", self._args[0])
2019-03-05 07:49:15 +01:00
self._processHandle.terminate()
2019-03-05 08:24:55 +01:00
while self.isRunning:
pass
return self._processHandle.returnCode
logging.debug("process not running: %s", self._args[0])
return 0
2019-03-04 19:43:32 +01:00
def readline(self):
"""!Read one line from stdout stream or None"""
2019-03-05 07:49:15 +01:00
if self.isRunning and self._stdout is not None:
try:
line = self._processHandle.stdout.readline().strip()
except UnicodeDecodeError:
return None
if line != "":
return line
2019-03-04 19:43:32 +01:00
return None
def setStdin(self, stdin):
"""!Set the stdin stream"""
self._stdin = stdin
def setStdout(self, stdout):
"""!Set the stdout stream"""
self._stdout = stdout
def setStderr(self, stderr):
"""!Set the stderr stream"""
self._stderr = stderr
@property
def stdout(self):
"""!Get the stdout stream"""
return self._processHandle.stdout
@property
def stderr(self):
"""!Get the stderr stream"""
return self._processHandle.stderr
2019-03-05 07:49:15 +01:00
@property
def isRunning(self):
if self._processHandle:
if self._processHandle.poll() is None:
return True
return False