TypeError:需要一个类似字节的对象,而不是'int'python3 [英] TypeError: a bytes-like object is required, not 'int' python3

查看:115
本文介绍了TypeError:需要一个类似字节的对象,而不是'int'python3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将内容写入JSON文件.它在Python2中很好用.但是由于Bytes概念的引入,它在Python3中失败了.因此,为了使其正常工作,我将str转换为字节并成功转换.之后,我检查了类型,以字节为单位.现在python3再次向我显示错误,即使它以字节为单位. 我的错误:

I am writing a contents to JSON file. It works great in Python2 . But it fails in Python3 due to the introduction of Bytes concept. So to make it work, i converted str to bytes and converted successfully. After that, i checked the type and it was in bytes. Now python3 shows me a error again even it was in bytes. My Error:

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)

推荐答案

二进制模式下文件对象的writelines方法期望将字节对象序列作为参数,但是您只是将字节对象传递给它对象,因此当writelines方法将bytes对象视为一个序列并对其进行迭代时,由于byte对象只是一个整数序列,因此每次迭代都会获取一个整数.

The writelines method of a file object in binary mode expects a sequence of bytes objects as a parameter, and yet you're passing to it just a bytes object, so when the writelines method treats the bytes object as a sequence and iterates over it, it gets an integer for each iteration since a bytes object is simply a sequence of integers.

您应该改用write方法:

f.write(_entry.encode())

这篇关于TypeError:需要一个类似字节的对象,而不是'int'python3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆