python 执行shell命令并将结果保存的实例
方法1:将shell执行的结果保存到字符串
defrun_cmd(cmd): result_str='' process=subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE) result_f=process.stdout error_f=process.stderr errors=error_f.read() iferrors:pass result_str=result_f.read().strip() ifresult_f: result_f.close() iferror_f: error_f.close() returnresult_str
方法2:将shell执行的结果写入到指定文件
defrun_cmd2file(cmd): fdout=open("file_out.log",'a') fderr=open("file_err.log",'a') p=subprocess.Popen(cmd,stdout=fdout,stderr=fderr,shell=True) ifp.poll(): return p.wait() return
以上这篇python执行shell命令并将结果保存的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。