我试图在Python 3中运行名为msgpack_checker.py
的以下脚本:
import msgpack
from faker import Faker
import logging
from logging.handlers import RotatingFileHandler
fake = Faker()
fake.seed(0)
data_file = "my_log.log"
logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)
handler = RotatingFileHandler(data_file, maxBytes=2000, backupCount=10)
handler.terminator = "" # Suppress the newline character (only works in Python 3)
logger.addHandler(handler)
fake_dicts = [{'name': fake.name()} for _ in range(100)]
for item in fake_dicts:
dump_string = msgpack.packb(item)
# print dump_string
logger.debug(dump_string)
unpacker = msgpack.Unpacker(open(data_file))
print("Printing unpacked contents:")
for unpacked in unpacker:
print(unpacked)
当我使用Python 2运行它时,它会打印以下输出:
Printing unpacked contents:
{'name': 'Joshua Carter'}
10
{'name': 'David Williams'}
10
{'name': 'Joseph Jones'}
10
{'name': 'Gary Perry'}
10
{'name': 'Terry Wells'}
10
{'name': 'Vanessa Cooper'}
10
{'name': 'Michael Simmons'}
10
{'name': 'Nicholas Kline'}
10
{'name': 'Lori Bennett'}
10
数字" 10"我相信来自记录器,应该通过handler.terminator = ""
命令在Python 3中删除。但是,如果我尝试使用python3 msgpack_checker.py
运行脚本,则会收到以下错误:
Traceback (most recent call last):
File "msgpack_checker.py", line 3, in <module>
import logging
File "/home/kurt/Documents/Scratch/logging/__init__.py", line 26, in <module>
import sys, os, time, cStringIO, traceback, warnings, weakref
ImportError: No module named 'cStringIO'
显然,logging
模块会尝试直接导入cStringIO
,而Python 3中已不再存在该模块。我已经看到了涉及从StringIO
导入io
的修复程序而不是StringIO
,但我不确定他们会在这里工作。关于如何让这个脚本在Python 3中工作的任何建议?
答案 0 :(得分:1)
正如几条评论所指出的,我不小心将目录logging
留在同一目录中,这是错误消息所指的内容。删除该目录后,我收到一条不同的错误消息,
Printing unpacked contents:
Traceback (most recent call last):
File "msgpack_checker.py", line 27, in <module>
for unpacked in unpacker:
File "msgpack/_unpacker.pyx", line 459, in msgpack._unpacker.Unpacker.__next__ (msgpack/_unpacker.cpp:459)
File "msgpack/_unpacker.pyx", line 380, in msgpack._unpacker.Unpacker._unpack (msgpack/_unpacker.cpp:380)
File "msgpack/_unpacker.pyx", line 370, in msgpack._unpacker.Unpacker.read_from_file (msgpack/_unpacker.cpp:370)
TypeError: expected bytes, str found
但这是一个单独的问题;至少导入logging
是成功的。