TypeError:需要一个类似字节的对象,而不是“ int” python3

时间:2019-02-16 07:22:17

标签: python json python-3.x

我正在将内容写入JSON文件。它在Python2中很好用。但是由于Bytes概念的引入,它在Python3中失败了。因此,为了使其正常工作,我将str转换为字节并成功转换。之后,我检查了类型,以字节为单位。现在,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)

1 个答案:

答案 0 :(得分:3)

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

您应该改用write方法:

f.write(_entry.encode())