温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-12-07 15:21:20 来源:亿速云 阅读:373 作者:Leah 栏目:开发技术

本篇文章为大家展示了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命令操作非系统自带工具时,最好带上工具路径。

补充知识:python 如何判断调用系统命令是否执行成功

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

>>> os.system('ls')
anaconda-ks.cfg install.log.syslog 模板 图片 下载 桌面
install.log     公共的           视频 文档 音乐
0
>>>
>>> os.system('lss')
sh: lss: command not found
32512
>>>

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

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

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

>>> if os.system('lss') !=0:print 'Without the command'
...
 
sh: lss: command not found
Without the command

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

>>> if os.system('ls') !=0:print 'Without the command'
...
 
anaconda-ks.cfg install.log.syslog 模板 图片 下载 桌面
install.log     公共的           视频 文档 音乐
>>>

上述内容就是python执行shell命令无法获取返回值如何解决,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI