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: # 执行失败
重新调整了之后可以将实时内容和执行状态都做拿到,但是亲测感觉效率并不好,还有没有更好的办法呢?
相关推荐
dingwun 2020-11-16
yuuuuy 2020-01-06
Laozizuiku 2019-12-06
liusarazhang 2019-10-22
codeAB 2019-10-20
oXiRiShi 2019-03-26
paopao00 2019-07-01
youandme 2019-07-01
PythonGCS 2018-05-12
jerry0 2018-05-11
赵家小少爷 2020-05-06
lhxxhl 2020-04-21
kkpiece 2020-03-03
skdzyl 2020-03-01
mieleizhi0 2020-03-01
猛禽的编程艺术 2020-02-02
onetozero 2019-12-30
赵家小少爷 2019-12-09