当前位置: 移动技术网 > IT编程>脚本编程>Python > python 执行shell命令并将结果保存的实例

python 执行shell命令并将结果保存的实例

2018年06月17日  | 移动技术网IT编程  | 我要评论

heyzo 0408,联谊代孕,吉林医药学院吧

方法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命令并将结果保存的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网