import subprocess
CHECK_SCRIPT = "test.py"
# 过滤 master_ip
waf_ip_list = filter(lambda x: x!= master_ip, set(waf_ips.split(',')))
waf_ips = ",".join(waf_ip_list)
# 检查进程CHECK_SCRIPT是否在运行
p = Popen("ps aux | grep {} | grep -v grep".format(CHECK_SCRIPT), stdout=PIPE,shell=True)
output_p = p.stdout.readlines()
if output_p:
return JsonResponse({'code': 0, 'msg': '脚本正在运行,请稍后再试'})
else:
cmd = 'python {}'.format(CHECK_SCRIPT)
res = subprocess.Popen(cmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
err = res.stderr.read()
if error:
cmd_res = err
else:
cmd_res = res.stdout.read()
return JsonResponse({'code': 0, 'msg': cmd_res)
知识点
-
灵活使用高阶函数
filter(),lambda(),map(),reduce()等 -
ps aux | grep test.py | grep -v grepgrep:查找含有指定字段的行
grep -v:反向查找,查找不含有指定字段的行在这里,我想查看
test.py是否在运行,使用grep命令进行过滤查找,而grep本身也是一个进程,所以需要把grep自身的进程过滤掉例如:
cat test.log | grep "login"|grep -v "deviceType"找出
test.log中包含login信息的,且没有deviceType这个字段的 -
利用管道机制
subprocess.PIPE实现非阻塞模式
本文介绍如何使用Python的subprocess模块检查特定脚本是否正在运行,并通过高阶函数filter()和lambda()过滤进程列表。同时,利用管道机制subprocess.PIPE实现非阻塞模式,提高程序效率。
727

被折叠的 条评论
为什么被折叠?



