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 cookbook(数据结构与算法)从任意长度的可迭代对象中分解元素操作示例

Python cookbook(数据结构与算法)从任意长度的可迭代对象中分解元素操作示例

本文实例讲述了python从任意长度的可迭代对象中分解元素操作。分享给大家供大家参考,具体如下: 从某个可迭代对象中分解出N个元素,但是可迭代对象的长度可能超过N,会出现“分解值过多”的...

Python Xml文件添加字节属性的方法

实例如下所示: from xml.etree.cElementTree import ElementTree,Element import xlrd import re def re...

解决python中用matplotlib画多幅图时出现图形部分重叠的问题

1.解决方法:使用函数 tight_layout() 2.具体使用方法 import matplotlib.pyplot as plt fig = plt.figure()...

selenium+python自动化测试之使用webdriver操作浏览器的方法

WebDriver简介 selenium从2.0开始集成了webdriver的API,提供了更简单,更简洁的编程接口。selenium webdriver的目标是提供一个设计良好的面向对...

关于Numpy数据类型对象(dtype)使用详解

常用方法 #记住引入numpy时要是用别名np,则所有的numpy字样都要替换 #查询数值类型 >>>type(float) dtype('float64') #...