python 执行shell命令无法获取返回值的解决方法
2018-03-21 12:05
721 查看
问题背景:利用python获取服务器中supervisor状态信息时发现未能获取到返回值。
python获取执行shell命令后返回值得几种方式:# 1.os模块
ret = os.popen("supervisorctl status")
ret_data = ret.read()
# 2.subprocess模块
ret = subprocess.Popen('supervisorctl status',shell=True,stdout=subprocess.PIPE)
out,err = ret.communicate()
# 3.commands模块
ret_data = commands.getoutput("supervisorctl status")
# 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命令操作非系统自带工具时,最好带上工具路径。
python获取执行shell命令后返回值得几种方式:# 1.os模块
ret = os.popen("supervisorctl status")
ret_data = ret.read()
# 2.subprocess模块
ret = subprocess.Popen('supervisorctl status',shell=True,stdout=subprocess.PIPE)
out,err = ret.communicate()
# 3.commands模块
ret_data = commands.getoutput("supervisorctl status")
# 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命令操作非系统自带工具时,最好带上工具路径。
相关文章推荐
- 无法获取IP地址,运行“ipconfig/renew”命令后提示“RPC服务器不可用”的解决方法
- python学习五:执行linux命令的两种方法、提高运行效率、进制转换、切片详解、ip和mac获取
- WORD"对话框打开时命令无法执行"的解决方法
- CM安装好集群之后在shell命令下执行hive 或者hbase操作遇到权限问题的解决方法
- 解决:shell脚本中,无法执行time命令,以统计某个程序执行时间
- 获取python执行shell命令的结果
- python执行shell获取硬件参数写入mysql的方法
- python3+nltk3+matplotlib1.3中plot方法无法执行的解决办法
- python中执行shell命令的几个方法小结
- 解决:shell脚本中,无法执行time命令,以统计某个程序执行时间
- 手把手教你:Ubuntu下cron定时执行命令无法成功执行的解决方法
- 无法获取IP地址,运行“ipconfig/renew”命令后提示“RPC服务器不可用”的解决方法
- python2.7 执行cmd命令及shell命令封装方法
- python中执行shell命令的几个方法小结
- java 中调用window系统中的文件,或者执行命令(shell、.CMD、.EXE)并获取返回值(如果有的话)
- WORD对话框打开时命令无法执行的解决方法
- linux crontab 无法执行shell脚本解决方法
- python调用其它脚本:pig,python,shell等等 (如何获取pig脚本执行的返回值)
- python执行shell命令的方法
- python调用其它脚本:pig,python,shell等等 (如何获取pig脚本执行的返回值)