python 执行shell命令并将结果保存的实例
更新时间:2018年05月11日 10:38:37 作者:siqi_fighting
今天小编就为大家分享一篇python 执行shell命令并将结果保存的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
方法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基本数据结构中的列表、元组、集合、字典相关概念、使用方法及推导式、遍历等相关使用技巧,需要的朋友可以参考下2019-03-03


最新评论