首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在将代码迁移到TypeError时解析Python3

如何在将代码迁移到TypeError时解析Python3
EN

Stack Overflow用户
提问于 2020-02-03 17:09:49
回答 1查看 71关注 0票数 0

我使用2到3模块将我的python脚本从2.7迁移到3,现在我正在尝试使用out...Can来解释我需要在这里修改什么?

代码语言:javascript
复制
found_qr = None
while not found_qr:
    keep_alive(1,5)
    time.sleep(4)
    process = None
    stdout_list = None
    process = subprocess.Popen('grep -E -o ".Source QR CODE :.{0,65}" ' + latest_file + ' | tail -1', shell=True, stdout=subprocess.PIPE,)
    stdout_list = process.communicate()
    stdout_list = stdout_list[0]
    if stdout_list.find("Source QR CODE") == -1:
        found_qr = None
    else:
        found_qr = 'found!'

我得到了这个错误:

代码语言:javascript
复制
if stdout_list.find("Source QR CODE") == -1:
TypeError: argument should be integer or bytes-like object, not 'str'

知道吗?谢谢!

更新:下面是我看到的一个类似的问题:

代码语言:javascript
复制
keep_alive(1,1)
process = subprocess.Popen('grep -E -o ".Source QR CODE :.{0,65}" ' + latest_file + ' | tail -1', shell=True, stdout=subprocess.PIPE,)
stdout_list = process.communicate()
qr_code = stdout_list[0].replace('Source QR CODE : ','')
qr_code = qr_code.replace(' ','')
qr_code = qr_code.replace('\n', '')
qr_code = str(qr_code)

TypeError:需要一个类似字节的对象,而不是'str‘。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-03 17:19:15

stdout_list = process.communicate()中,您可以得到一个bytes列表,因此stdout_list[0]是一个字节对象。

stdout_list.find("Source QR CODE")中,您试图在这个字节对象中找到一个字符串,因为bytes is different from str in Python 3无法工作。

由于此字符串是常量,因此可以轻松地将其转换为bytes对象:

代码语言:javascript
复制
stdout_list.find(b"Source QR CODE")  # note the `b` before the string literal

或适当地编码此字符串:

代码语言:javascript
复制
stdout_list.find("Source QR CODE".encode('ascii'))  # here you can use whatever encoding you need

正如错误消息告诉您的,您可以搜索“类似字节的对象”和整数,因为字节对象实际上是0到255之间的整数列表:

代码语言:javascript
复制
>>> b'thing'  # this is a bytes object
b'thing'
>>> list(_)
[116, 104, 105, 110, 103]  # actually a bunch of integers (bytes)
>>> b'thing'.find(116)  # find a single byte
0
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60043979

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档