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

yipeiwu_com5年前Python基础

方法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如何使用unittest测试接口

本文实例为大家分享了python使用unittest 测试接口的具体代码,供大家参考,具体内容如下 1.首先使用 python 的requests 对接口进行测试 # TestInf...

python 批量修改 labelImg 生成的xml文件的方法

概述 自己在用labelImg打好标签后,想只用其中几类训练,不想训练全部类别,又不想重新打标生成.xml文件,因此想到这个办法:直接在.xml文件中删除原有的不需要的标签类及其属性。...

Python实现压缩和解压缩ZIP文件的方法分析

本文实例讲述了Python实现压缩和解压缩ZIP文件的方法。分享给大家供大家参考,具体如下: 有时我们需要在 Python 中使用 zip 文件,而在1.6版中,Python 就已经提供...

Python 操作mysql数据库查询之fetchone(), fetchmany(), fetchall()用法示例

本文实例讲述了Python 操作mysql数据库查询之fetchone(), fetchmany(), fetchall()用法。分享给大家供大家参考,具体如下: demo.py(查询,...

程序员写Python时的5个坏习惯,你有几条?

很多文章都有介绍怎么写好 Python,我今天呢,相反,说说写代码时的几个坏习惯。有的习惯会让 Bug 变得隐蔽难以追踪,当然,也有的并没有错误,只是个人觉得不够优雅。 注意:示例代码在...