ITPub博客

首页 > IT职业 > IT生活 > python如何调用subprocess模块实现外部命令?

python如何调用subprocess模块实现外部命令?

IT生活 作者:ldzsl 时间:2021-09-11 10:07:32 0 删除 编辑

当我们写python脚本的时候看,如果需要调用外部命令,有很多的模板可以使用,标准包里面的os.popen,os.system,commands.getstatusoutput, 但是这些现在都是不推荐的了,现在标准包推荐使用的是subprocess模块,使用上一般会使用如下函数来进行封装,这样是比较好用的,那接下来就跟大家说实现方法吧~

直接给大家上实现代码演示:

def run(cmd):
 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
 out, err = p.communicate()
 print ('cmd=[{}] out=[{}] err=[{}] returncode=[{}]'.format(cmd, out, err, p.returncode))
 if p.returncode != 0:
 raise Exception('cmd run error')
 return out

通过上述的实现代码演示,我们可以直接调用run函数来运行命令,得到命令的标准输出,在返回码非0的情况下,直接抛出异常。好啦,大家都消化学习吧,更多学习内容,尽在python学习网。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2325/viewspace-2832035/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2016-01-19

  • 博文量
    72
  • 访问量
    12922