python 执行shell命令无法获取返回值的解决方法

妖狐艹你老母 2022-05-29 09:17 448阅读 0赞

问题背景:利用python获取服务器中supervisor状态信息时发现未能获取到返回值。

python获取执行shell命令后返回值得几种方式:

  1. # 1.os模块
  2. ret = os.popen("supervisorctl status")
  3. ret_data = ret.read()
  4. # 2.subprocess模块
  5. ret = subprocess.Popen('supervisorctl status',shell=True,stdout=subprocess.PIPE)
  6. out,err = ret.communicate()
  7. # 3.commands模块
  8. ret_data = commands.getoutput("supervisorctl status")
  9. # commands.getstatusoutput()还可获取到命令执行是否成功状态

一开始程序使用的是 os.popen() 方法,在交互式python shell或者IDE环境下使用上述方法都可以获取到执行的返回值,但当使用脚本执行时发现返回值为空,然后修改为使用 command.getoutput() 方法,这时获取到返回值为 “sh: supervisorctl: command not found”。由此可知是执行命令时无法识别 supervisorctl 命令,但系统中是已经安装好supervisor的,于是使用 which supervisorctl 查看supervisorctl路径,以带路径的方式执行指令 “/usr/local/bin/supervisorctl status”,最后成功获取到返回值。

总结,python使用shell命令操作非系统自带工具时,最好带上工具路径。

发表评论

表情:
评论列表 (有 0 条评论,448人围观)

还没有评论,来说两句吧...

相关阅读