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 @property使用方法解析

1. 作用 将类方法转换为类属性,可以用 . 直接获取属性值或者对属性进行赋值 2.实现方式 使用property类来实现,也可以使用property装饰器实现,二者本质是一样的。多...

Python 结巴分词实现关键词抽取分析

Python 结巴分词实现关键词抽取分析

1 简介 关键词抽取就是从文本里面把跟这篇文档意义最相关的一些词抽取出来。这个可以追溯到文献检索初期,当时还不支持全文搜索的时候,关键词就可以作为搜索这篇论文的词语。因此,目前依然可以...

Python安装使用命令行交互模块pexpect的基础教程

一、安装 1、安装easy_install工具 wget http://peak.telecommunity.com/dist/ez_setup.py python ez_se...

Python list与NumPy array 区分详解

1. 数据类型 type() #!/usr/bin/env python # -*- coding: utf-8 -*- # Yongqiang Cheng from __fut...

Python多线程应用于自动化测试操作示例

Python多线程应用于自动化测试操作示例

本文实例讲述了Python多线程应用于自动化测试操作。分享给大家供大家参考,具体如下: 多线程执行测试用例 实例: import threading from time import...