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

yipeiwu_com6年前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 Django 页面上展示固定的页码数实现代码

Python Django 页面上展示固定的页码数实现代码

如果页数太多的话,全部显示在页面上就会显得很冗杂 可以在页面中显示规定的页码数 例如: book_list.html: <!DOCTYPE html> <htm...

Python创建文件和追加文件内容实例

一、用Python创建一个新文件,内容是从0到9的整数, 每个数字占一行: 复制代码 代码如下: #python >>>f=open('f.txt','w')&nbs...

Python使用wxPython实现计算器

本文实例为大家分享了wxPython实现计算器的具体代码,供大家参考,具体内容如下 # -*- coding: utf-8 -*- ########################...

python使用webbrowser浏览指定url的方法

本文实例讲述了python使用webbrowser浏览指定url的方法。分享给大家供大家参考。具体如下: 这段代码提示用户输入关键词,通过webbrowser打开浏览器浏览google...

Python实现数值积分方式

Python实现数值积分方式

原理: 利用复化梯形公式,复化Simpson公式,计算积分。 步骤: import math """测试函数""" def f(x,i): if i == 1: re...