1、shell
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和resultjson
2、spa
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)
成功解決以前的問題,可將命令的執行結果實時更新,可是在執行結束以後並不能得知其執行狀態是成功或失敗code
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: # 執行失敗
從新調整了以後能夠將實時內容和執行狀態都作拿到,可是親測感受效率並很差,還有沒有更好的辦法呢?blog