def __init__(self, sProcName, nTimeOut): print_t(sProcName) #print '\n' temp = sProcName.split('>') #print temp #print temp[0] self.sProcName = sProcName self.nTimeOut = nTimeOut #stdout = subprocess.PIPE表示子进程的标准输出会被重定向到特定管道,这样父进程和子进程就可以通讯了 #如果shell = True,表示目录执行程序,由Shell进程调起。 #中间会产生以下流程:创建shell(cmd)进程,shell(cmd)进程创建目标进程。这样的话,目标进程是本进程的孙子进程,而不是子进程 #可以推测,cmd窗口中命令行输出重定向到文件,应该也是这种实现方式 self.proc = subprocess.Popen(temp[0], stdout=subprocess.PIPE, shell=False) if self.proc != None and self.nTimeOut != None: t1 = timeOutThread(self, self.nTimeOut) t1.start() target = None if len(temp) == 2: target = temp[1].replace(" ", "") #print target if self.proc != None: t2 = redirecThread(self.proc, target) t2.start()
def __init__(self, proc, target): threading.Thread.__init__(self) self.proc = proc self.target = target self.file = None self.proc_exited = False if target != None and len(target)!= 0: self.target = target try: self.file = open(self.target, 'w') except Exception, e: print_t(str(e))
def run(self): while True: buffer = self.proc.stdout.readline() if len(buffer) == 0: #print 'read end' print_t('read end') #print '\n' break if buffer.startswith('\r\n'): continue buffer = buffer.replace("\r\n", "") #print buffer if self.file == None: print buffer else: self.file.write(buffer)
def run(self): child_proc = None while True: prompt = '>' if child_proc != None and child_proc.isAlive(): prompt = "" try: pass strInput = raw_input(prompt) #不包含换行符Ctrl+C会抛异常 except Exception, e: print_t(str(e)) continue if child_proc != None and child_proc.isAlive(): try: strInput = strInput.decode('gbk').encode( 'utf8') #输入可能是utf8编码 except Exception, e: pass child_proc.write(strInput) child_proc.write('\n') if strInput == 'exit': child_proc.wait() continue
class workThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): child_proc = None while True: prompt = '>' if child_proc != None and child_proc.isAlive(): prompt = "" try: pass strInput = raw_input(prompt) #不包含换行符Ctrl+C会抛异常 except Exception, e: print_t(str(e)) continue if child_proc != None and child_proc.isAlive(): try: strInput = strInput.decode('gbk').encode( 'utf8') #输入可能是utf8编码 except Exception, e: pass child_proc.write(strInput) child_proc.write('\n') if strInput == 'exit': child_proc.wait() continue if strInput == "exit": break if strInput == "": continue if pre_process(strInput): continue try: child_proc = syos.SelfProcess(strInput, None) #proc.wait() except Exception, e: pass print_t(str(e))
def terminate(self): if self.proc != None and self.proc.poll() == None: print_t('terminate') #print '\n' self.proc.terminate()