前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python3 subprocess.check_output返回值转string

Python3 subprocess.check_output返回值转string

作者头像
Cloudox
发布2021-11-23 14:58:39
2730
发布2021-11-23 14:58:39
举报
文章被收录于专栏:月亮与二进制月亮与二进制

Python3中的subprocess.check_output函数可以执行一条sh命令,并返回命令的输出内容,用法如下:

代码语言:javascript
复制
output = subprocess.check_output(["python3", "xx.py"], shell = False)

该函数两个参数第一个表示命令内容,因为中间有空格所以用中括号这种形式,同时制定shell=False表示命令分开写了。而该命令执行后的输出内容会返回给output变量。

需要注意的是这个output变量并不是一个string,也就是说不能用string的一些函数,比如你想知道返回的输出中是否包含某个字符串:

代码语言:javascript
复制
output = subprocess.check_output(["python3", "xx.py"], shell = False)
if (output.find("yes") >= 0): print("yes")
else: print("no")

这样执行后不会有任何输出,因为find()函数是给string用的,而这里的output其实不是一个string,那它是个什么呢?

我们看看python3的subprocess.check_output的文档

By default, this function will return the data as encoded bytes. The actual encoding of the output data may depend on the command being invoked, so the decoding to text will often need to be handled at the application level.

也就是说,返回的其实是一个编码后的比特值,实际的编码格式取决于调用的命令,因此python3将解码过程交给应用层,也就是我们使用的人来做。

这样就清晰了,要对输出使用stirng的操作,需要先通过解码将其转换成string:

代码语言:javascript
复制
output = subprocess.check_output(["python3", "xx.py"], shell = False)
out = output.decode()
if (out.find("yes") >= 0): print("yes")
else: print("no")

这样就可以正常判断了。

查看作者首页

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018/1/19 上,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档