subprocess 使用一例,subprocess使用,用subprocess实


用subprocess实现的简易expect

#-*- coding:utf-8 -*-import subprocessimport sys,osimport time#支持windows系统if os.name <> "nt": exit(1)class spawn:    timeout = 0.2    client = None    def __init__(self,cmd_str='cmd',timeout = 0.2):        self.client = subprocess.Popen(cmd_str, stdin = subprocess.PIPE,stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True)    def expect(self,expect_str = ">",timeout = 0.2):        _wait_time_start = time.time()        _expect_len = len(expect_str)        while self.client.poll() is None:            _wait_time_end = time.time()            output = self.client.stdout.readline()            if len(output.strip()) > _expect_len:                if output.strip()[-_expect_len::] == expect_str:                    break                else:                    sys.stdout.write(output)                    self.send()            if round((_wait_time_end - _wait_time_start),2) > self.timeout:                break    def send(self,send_str='\r\n'):        self.client.stdin.write(send_str)        self.client.stdin.flush()    def output(self):        if self.client.poll() is None:            out = self.client.communicate(input='\r\n')[0]            sys.stdout.write(out)        else:            sys.stdout.write("pid is close\n")    def close(self):        out = self.client.communicate()[0]        sys.stdout.write(out)        if self.client.poll() is None:            self.client.kill()    def pid(self):        return self.client.pidm = spawn("wmic")print "pid:",m.pid()m.send("cpu list\r\n")m.send("cpu list\r\n")m.send("?\r\n")m.output()del mnetsh = spawn("netsh")print "pid:",netsh.pid()netsh.send("help\r\n")netsh.send("show\r\n")  netsh.send("quit\r\n")netsh.output()del netsh# test()

评论关闭