gpt4 book ai didi

python - 类型错误 : a bytes-like object is required, 不是 'int' python3

转载 作者:行者123 更新时间:2023-12-01 01:12:30 29 4
gpt4 key购买 nike

我正在将内容写入 JSON 文件。它在 Python2 中运行得很好。但在Python3中由于引入了Bytes概念而失败了。因此,为了使其工作,我将 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)

最佳答案

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

您应该使用 write 方法:

f.write(_entry.encode())

关于python - 类型错误 : a bytes-like object is required, 不是 'int' python3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54720820/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com