python--终端工具之subprocess

一、

subprocess.getstatusoutput
import subprocess
cmd = ‘ifconfig‘
def cmds(cmd,print_msg=True):
    status,result = subprocess.getstatusoutput(cmd)
    if status > 0:
        return {"status":"failed","msg":result}
    return {"status":"succeed","msg":result}

可以将执行之后的状态和执行结果反馈,但是痛点:result是一次性返回,简单的说就是,比如你执行一条ping www.baidu.com的命令,程序一直是在执行状态,无任何输出,只当执行结束后返回status和result

二、

subprocess.Popen
import subprocess
cmd = ‘ping www.baidu.com‘
def cmds(cmd,print_msg=True):
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    print(p.stderr)
    lines = []
    for line in iter(p.stdout.readline, b‘‘):
        line = line.rstrip().decode(‘utf8‘)
        if print_msg:
            print(">>>", line)
if __name__ == ‘__main__‘:
    
    cmds(cmd)

成功解决之前的问题,可将命令的执行结果实时更新,但是在执行结束之后并不能得知其执行状态是成功或失败

def cmds(self,cmds, print_msg=True):
        compilePopen = subprocess.Popen(cmds,shell=True,stdout=subprocess.PIPE,close_fds=True,stderr=subprocess.STDOUT)
        compilePopen.wait()    # 没有这个无法得知compilePopen.returncode状态是否成功
        for line in iter(compilePopen.stdout.readline, b‘‘):
            msg = line.rstrip().decode(‘utf8‘)if print_msg:
                self.ws.send(json.dumps({
                    "progress": "run_script",
                    "msg": msg,
                    ‘ctime‘: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                    ‘user‘: self.task.username
                }))
        # if compilePopen.returncode >= 0:  # 执行成功     
        # else:  # 执行失败

重新调整了之后可以将实时内容和执行状态都做拿到,但是亲测感觉效率并不好,还有没有更好的办法呢?

 

相关推荐