Python执行Shell命令并保存结果的两种实现方式

洛溪
洛溪
发布时间:2026-10-13 | 3人浏览过
原创

本文介绍在Python中执行Shell命令的两种常见方法:一是通过subprocess模块捕获标准输出和错误流,将执行结果保存为字符串;二是将命令的标准输出和错误重定向至指定日志文件。文中提供了完整的代码示例,展示了如何处理进程状态及资源释放,适用于需要自动化执行系统命令并持久化结果的场景。

方法一:将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

方法二:将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 相关产品和应用

全部下载

专题列表