Python——检测Popen返回的stdOutMsg中是否是否包含指定字符,并提取指定位置的信息
问题背景:
Python 中经常会需要通过subprocess.PoPen函数下发Shell Command,与操作系统进行交互。一些情况下,还需要分析shell command的返回值,提取有用信息。
1、首先给出subporess.Popen下发shell command的接口示例:
def FilterPrintable(input_string=""):
printable = set(string.printable)
if isinstance(input_string, bytes):
try:
input_string = input_string.decode("utf-8", errors="replace")
except Exception as ex:
raise Exception(ex)
obj_filter = filter(lambda x: x in printable, input_string)
output_string = ''.join(c for c in obj_filter)
return output_string
def SendShellCommand(self, shellcmd="", timeOut=0):
try:
p = subprocess.Popen(shellcmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, universal_newlines=True)
if timeOut:
(stdOut, stdErr) = p.communicate(timeOut)
else:
(stdOut, stdErr) = p.communicate()
stdOutMsg = self.FilterPrintable(stdOut)
stdErrMsg = self.FilterPrintable(stdErr)
except subprocess.TimeoutExpired:
raise subprocess.TimeoutExpired
except Exception as ex:
raise Exception(ex)
if p.stdout:
p.stdout.close()
if p.stdErr:
p.stdErr.close()
try:
p.kill()
except OSError:
pass
return p.returncode, stdOutMsg, stdErrMsg
2、举例说明如何解决背景中所述 的问题:
def CheckFioProcess():
cmdStr = "ps -elf | grep fio"
returncode, stdOutMsg, stdErrMsg = self.SendShellCommand(cmdStr)
fioPidList = []
stdOutMsgList = stdoutMsg.spilt("\n")
for stdMsg in stdOutMsgList:
if stdMsg.find("fio") != -1:
index1 = stdMsg.find("root")
subStdoutMsg = stdMsg[index1+3:]
fioPid = int(re.findall("\d+", subStdoutMsg))[0])
fioPidList .append(fioPid)
else:
continue
return fioPidList