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常用模块logging——日志输出功能(示例代码)

用途 logging模块是Python的内置模块,主要用于输出运行日志,可以灵活配置输出日志的各项信息。 基本使用方法 logging.basicConfig(level=loggi...

Python创建普通菜单示例【基于win32ui模块】

Python创建普通菜单示例【基于win32ui模块】

本文实例讲述了Python创建普通菜单的方法。分享给大家供大家参考,具体如下: 一、代码 # -*- coding:utf-8 -*- #! python3 import win32...

基于python实现的百度音乐下载器python pyqt改进版(附代码)

基于python实现的百度音乐下载器python pyqt改进版(附代码)

前言 之前写过一个用python实现的百度新歌榜、热歌榜下载器的文章,实现了百度新歌、热门歌曲的爬取与下载。但那个采用的是单线程,网络状况一般的情况下,扫描前100首歌的时间大概得到40...

Python数据类型之Number数字操作实例详解

本文实例讲述了Python数据类型之Number数字操作。分享给大家供大家参考,具体如下: 一、Number(数字) 数据类型 为什么会有不同的数据类型? 计算机是用来做数学计算的机器,...

python笔记之mean()函数实现求取均值的功能代码

用法:mean(matrix,axis=0)  其中 matrix为一个矩阵,axis为参数 以m * n矩阵举例: axis 不设置值,对 m*n 个数求均值,返回一个实数...