python执行shell命令无法获取返回值如何解决

  介绍

本篇文章为大家展示了python执行shell命令无法获取返回值如何解决,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

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

 # 1.操作系统模块
  ret=os.popen (“supervisorctl status")
  ret_data=https://www.yisu.com/zixun/ret.read ()
  2. #子流程模块
  ret=子流程。Popen (supervisorctl地位,shell=True, stdout=subprocess.PIPE)
  ,呃=ret.communicate ()
  # 3.命令模块
  ret_data=命令。getoutput (“supervisorctl地位”)
  # commands.getstatusoutput()还可获取到命令执行是否成功状态

一开始程序使用的是os.popen()方法,在交互式python shell或者IDE环境下使用上述方法都可以获取到执行的返回值,但当使用脚本执行时发现返回值为空,然后修改为使用command.getoutput()方法,这时获取到返回值为“sh: supervisorctl:命令没有找到”。

由此可知是执行命令时无法识别supervisorctl命令,但系统中是已经安装好主管的,于是使用该supervisorctl查看supervisorctl路径,以带路径的方式执行指令“/usr/地方/bin/supervisorctl地位”,最后成功获取到返回值。

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

<强> python如何判断调用系统命令是否执行成功

首先我们要知道如何调用系统命令:

在祝辞祝辞os.system (& # 39; ls # 39;)   anaconda-ks。cfg install.log。syslog模板图片下载桌面   安装。日志公共的视频文档音乐   0   在在在   在在在os.system (& # 39; lss # 39;)   承宪:lss:命令没有找到   32512年   祝辞祝辞祝辞

\ \第一种,我们可以肉眼识别正确的会返回0,错误的则是非0

\ \第二种,使用如果判断调用系统命令返回值是否为0,如为0则不输出,不为0则输出“没有command"

- - - - - - - - - - - - - - - - - - -错误- - - - - - - - - - - - - - - - - - -

在祝辞祝辞如果os.system (& # 39; lss # 39;) !=0:打印& # 39;没有命令# 39;   …      承宪:lss:命令没有找到   没有命令

- - - - - - - - - - - - - - - - - - -正确- - - - - - - - - - - - - - - - - - -

在祝辞祝辞如果os.system (& # 39; ls # 39;) !=0:打印& # 39;没有命令# 39;   …      anaconda-ks。cfg install.log。syslog模板图片下载桌面   安装。日志公共的视频文档音乐   祝辞祝辞祝辞

python执行shell命令无法获取返回值如何解决