import subprocess
# 根据外部传入的lambda进行output处理,并可以设置超时时间
class ExecCmd:
@staticmethod
def get_output(cmd_str: str, func, timeout=3):
try:
result = subprocess.run([cmd_str], shell=True, capture_output=True, text=True, timeout=timeout)
if result.returncode == 0:
return (0, func(result.stdout))
return (result.returncode, None)
except Exception as e:
print(f"exception, error:{e}")
return -1, None
a = ExecCmd.get_output("ps -ef | grep bash | grep -v grep | awk '{print $2}'", lambda res : res.splitlines())
print(a)