【发布时间】:2015-07-15 10:11:33
【问题描述】:
我正在从事一个处理解析电子邮件并将其保存到数据库的项目。解析电子邮件并将解析的电子邮件保存到日志文件中没有问题,但是当我尝试从日志文件中读取时,我遇到了一个奇怪的问题。代码如下:
def main():
global email_batch, temp_email_batch
read_logfile = True
while read_logfile:
try:
with open('a-1-test.json', 'r') as outfile:
temp_email_batch = json.load(outfile)
outfile.close()
except IOError as err:
print "I/O error({0}): {1}".format(err.errno, err.strerror)
except:
print "Unexpected error:", sys.exc_info()[0]
if temp_email_batch != email_batch:
email_batch = temp_email_batch
print "not equal log files"
# saveData()
for parsedMail in email_batch:
collection.insert(parsedMail)
else:
print "equal log files"
time.sleep(10)
我可以读取日志文件(这里只是一个 json 格式的测试文件)并保存数据。检查:
if temp_email_batch != email_batch:
当我尝试比较两个批次时有一个奇怪的行为。这个想法是检查我是否已经从日志文件中获取数据,或者是否已将新数据写入日志文件。如果我注释掉迭代:
for parsedMail in email_batch:
# http_client.addRawData(sourceName, parsedMail)
collection.insert(parsedMail)
检查工作正常,并查看何时没有新数据添加到日志文件,但如果我取消注释,即使 temp_email_batch 与 email_batch 相等,检查似乎总是为真,因此它会不断将相同的电子邮件保存到集合。
我很震惊。迭代器是否以某种方式更改列表?我所有的编程直觉都说它没有,但是如果只是注释它,代码可以正常工作并且如果 temp 等于前一批,则跳转到 else 子句肯定有问题。
提前谢谢你, 乔治
编辑:
因此,我找到了一种解决方法,即不直接通过 pymongo 库将我的数据保存到数据库,而是使用 json 远程进程调用并设置一个脚本,该脚本定义了几种用于数据库操作的方法。通过使用 RPC,我没有任何问题,并且代码工作正常。
【问题讨论】:
-
我想说python正在检查
temp_email_batch和email_batch是否是不同的实体,而不是它们的内容是否不同。您可能需要实现此比较才能使其正常工作。 -
你可以试试
if all(email in email_batch for email in temp_email_batch): -
@cnluzon,恐怕这是不正确的。在 Python 中进行身份测试的是
is运算符。这仍然只是一个平等测试。 -
对了,不应该是
for parsedMail in temp_email_batch还是我理解你的问题有误? -
老实说,我敢打赌这是因为您使用的是 Mongo,它会在您保存后为每个字典添加一个
_id字段。这将使生成的变异字典列表无法通过相等性测试。
标签: python list dictionary iterator