菜鸟笔记
提升您的技术认知

python subprocess.popen 实时输出 stdout(正确管道写法)-ag真人游戏

大部分的程序是这样的:

from subprocess import popen, pipe, stdout
p = popen(cmd, stdout=pipe, stderr=stdout, shell=true)
while true:
    print(p.stdout.readline())
    if not line: 
        break

但是由于子程序没有进行 flush 的话,会把结果缓存到系统中。导致程序运行完成,上面的程序才会进行打出(会一直卡在readline这个函数)。

解决方法:

p = subprocess.popen(cmd, stdout=subprocess.pipe, bufsize=1)
for line in iter(p.stdout.readline, b''):
    print line,
p.stdout.close()
p.wait()

实际弱口令我是这样写的

import subprocess     #popen
proc = subprocess.popen(medusacmd, stdout=subprocess.pipe, stderr=subprocess.stdout, shell=true)
for line in iter(proc.stdout.readline, 'b'):
    print line
    if not subprocess.popen.poll(proc) is none:
        if line == "":
            break
proc.stdout.close()

记小的写法

proc = subprocess.popen(cmd, shell=true, stdout=subprocess.pipe, stderr=subprocess.stdout)
try:
    while true:
        buff = proc.stdout.readline()
        print(buff)
        if buff == '' and proc.poll() != none:
            break
        else:
            .....
except exception:
    data["status"] = -1
finally:
    return data

单次管道输出写法

方法一

# -*- coding: utf-8 -*-
import re
import sys
import subprocess
from subprocess import popen, pipe, stdout
#docker_info = {"container id":"", "name":"", "cpu %":"", "mem usage / limit":"", \
#               "mem %":"", "net i/o":"", "block i/o":"", "pids":""}
docker_list = []
cmd = "docker stats -a --no-stream"
proc = subprocess.popen(cmd, shell=true, stdout=subprocess.pipe, stderr=subprocess.stdout)
try:
    buff = proc.communicate()
    stritem = buff[0]
    str_list = re.split(r'   |\n', stritem)
    for i in range(8, len(str_list)-1):
        if i % 8 == 0:
            value = 0
            docker_info = {}
            docker_info["container id"] = str_list[i]
        else:
            value  = 1
            if value == 1:
                docker_info["name"] = str_list[i]
            elif value == 2:
                docker_info["cpu %"] = str_list[i]
            elif value == 3:
                docker_info["mem usage / limit"] = str_list[i]
            elif value == 4:
                docker_info["mem %"] = str_list[i]
            elif value == 5:
                docker_info["net i/o"] = str_list[i]
            elif value == 6:
                docker_info["block i/o"] = str_list[i]
            elif value == 7:
                docker_info["pids"] = str_list[i]
                docker_list.append(docker_info)
                value = 0
    print docker_list
except exception as e:
    print "error", e
    sys.exit(1)
    proc.stdout.close()

方法二(待测试)

import subprocess
from multiprocessing.dummy import pool as threadpool
command = poc   ' -t '   ip   ' -p '   port
result = subprocess.getoutput(command)
if 'warning: server is vulnerable' in result:
    result = aaaaa
else:
    result = bbbbbb

 

网站地图