python 执行shell命令并将结果保存的实例

请好好珍惜,因为今天是你往后日子里最年轻的一天。有了梦想,你就会有动力,有了动力,你才会有成功的希望。对待健康,偏见比无知更可怕!

方法1: 将shell执行的结果保存到字符串

def run_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()
 if errors: pass
 result_str = result_f.read().strip()
 if result_f:
  result_f.close()
 if error_f:
  error_f.close()
 return result_str

方法2:将shell执行的结果写入到指定文件

def run_cmd2file(cmd):
 fdout = open("file_out.log",'a')
 fderr = open("file_err.log",'a')
 p = subprocess.Popen(cmd, stdout=fdout, stderr=fderr, shell=True)
 if p.poll():
  return
 p.wait()
 return

以上这篇python 执行shell命令并将结果保存的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

您可能有感兴趣的文章
Python自动化运维-使用Python脚本监控华为AR路由器关键路由变化

Python自动化运维-netmiko模块设备自动发现

Python自动化运维—netmiko模块连接并配置华为交换机

Python自动化运维-利用Python-netmiko模块备份设备配置

Python3内置模块之json编码解码方法详解