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简单实现两个任意字符串乘积的方法示例

本文实例讲述了Python简单实现两个任意字符串乘积的方法。分享给大家供大家参考,具体如下: 题目: 给定两个任意数字组成的字符串,求乘积,字符可能很大,但是python具有无限精度的整...

python实现回旋矩阵方式(旋转矩阵)

我们知道Python中是没有数组 这种数据结构的,所以要想实现回旋矩阵,需要先导入一个numpy包, 它是一个由多维数组对象和用于处理数组的例程集合组成的python扩充程序库,可以用来...

python、Matlab求定积分的实现

python、Matlab求定积分的实现

python求定积分 计算 from sympy import * x = symbols('x') print(integrate(sin(2*x)/(1+x**2), (x,...

Python3.6连接Oracle数据库的方法详解

本文实例讲述了Python3.6连接Oracle数据库的方法。分享给大家供大家参考,具体如下: 下载cx_Oracle模块模块: https://pypi.python.org/pypi...

Django后端发送小程序微信模板消息示例(服务通知)

Django后端发送小程序微信模板消息示例(服务通知)

模板消息 官方文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/template-mess...