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中使用bidict模块双向字典结构的奇技淫巧

快速入门 模块提供三个类来处理一对一映射类型的一些操作 'bidict', 'inverted', 'namedbidict' >>> import bidict...

详解Python3注释知识点

Python3 注释 确保对模块, 函数, 方法和行内注释使用正确的风格 Python中的注释有单行注释和多行注释: Python中单行注释以 # 开头,例如:: # 这是一个...

python中requests和https使用简单示例

requests 是一个非常小巧全面的库,应用它可以很容易写出与服务器进行交互的程序,今天遇到了一个问题,与服务器交互时,url都是https开头的,都进行了ssl加密处理,这样一来,就...

Python进程池Pool应用实例分析

本文实例讲述了Python进程池Pool应用。分享给大家供大家参考,具体如下: 当需要创建的子进程数量不多时,可以直接利用multiprocessing中的Process动态成生多个进程...

Python的高级Git库 Gittle

Gittle是一个高级纯python git 库。构建在dulwich之上,提供了大部分的低层机制。 Install it pip install gittle Examples : C...