【问题标题】:TypeError: a bytes-like object is required, not 'int' python3TypeError:需要一个类似字节的对象,而不是'int' python3
【发布时间】:2019-07-10 06:36:30
【问题描述】:

我正在向 JSON 文件写入内容。它在 Python2 中运行良好。但由于引入了字节概念,它在 Python3 中失败了。所以为了让它工作,我将 str 转换为 bytes 并成功转换。之后,我检查了类型,它以字节为单位。现在 python3 再次向我显示一个错误,即使它是以字节为单位的。 我的错误:

PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
PING 192.168.1.47 (192.168.1.47) 56(84) bytes of data.
64 bytes from 192.168.1.47: icmp_seq=1 ttl=64 time=0.028 ms

--- 192.168.1.47 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.028/0.028/0.028/0.000 ms
64 bytes from 8.8.8.8: icmp_seq=1 ttl=45 time=59.6 ms

--- 8.8.8.8 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 59.606/59.606/59.606/0.000 ms
<class 'bytes'>
b'"February 16 2019, 12:57:01":{"monitor.ip": "192.168.1.47", "monitor.status": "UP"},\n'
Traceback (most recent call last):
  File "/home/paulsteven/BEAT/stack.py", line 38, in <module>
    f.writelines(_entry)
TypeError: a bytes-like object is required, not 'int'

代码如下:

import os
from multiprocessing import Pool
import json
import datetime
import time

hosts = ["192.168.1.47", "8.8.8.8"]
MAX_NUMBER_OF_STATUS_CHECKS = 2
FILE_NAME = 'hosts_stats.json'


#
# counter and sleep were added in order to simulate scheduler activity
#

def ping(host):
    status = os.system('ping -c 1 {}'.format(host))
    return datetime.datetime.now().strftime("%B %d %Y, %H:%M:%S"), {"monitor.ip": host,
                                                                "monitor.status": 'UP' if status == 0 else 'DOWN'}


if __name__ == "__main__":
    p = Pool(processes=len(hosts))
    counter = 0
    if not os.path.exists(FILE_NAME):
        with open(FILE_NAME, 'w') as f:
            f.write('{}')
    while counter < MAX_NUMBER_OF_STATUS_CHECKS:
        result = p.map(ping, hosts)
        with open(FILE_NAME, 'rb+') as f:
            f.seek(-1, os.SEEK_END)
            f.truncate()
            for entry in result:
                _entry = '"{}":{},\n'.format(entry[0], json.dumps(entry[1]))
                _entry = _entry.encode()
                print(type(_entry))
                print(_entry)
                f.writelines(_entry)
            f.write('}')
        counter += 1
        time.sleep(2)

【问题讨论】:

  • 向我们展示完整的错误回溯。
  • 添加了完整的错误详情

标签: python json python-3.x


【解决方案1】:

二进制模式下文件对象的writelines 方法需要一个字节对象序列作为参数,但您传递给它的只是一个字节对象,所以当writelines 方法将字节对象视为一个序列并对其进行迭代,每次迭代都会得到一个整数,因为字节对象只是一个整数序列。

您应该改用write 方法:

f.write(_entry.encode())

【讨论】:

  • Traceback(最近一次调用最后):文件“/home/paulsteven/BEAT/stack.py”,第 39 行,在 f.write('}') TypeError: a bytes- like 对象是必需的,而不是 'str'
  • 感谢您的回答。效果很好。我通过转换为 bytes=> f.write('}'.encode('ascii')) 清除了上述错误
猜你喜欢
  • 2017-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多