import imaplib, re
import os
while(True):
conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
conn.login("xxx", "xxxx")
unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1)
print unreadCount
if unreadCount > 10:
os.system('ls')
即使 unreadCount 小于 10,它也会运行命令“ls”。为什么?
最佳答案
您可能希望将该值强制转换为整数,如下所示:
unreadCount = int (re.search (blah, blah, blah).group (1))
对 re.search
的调用返回一个字符串,如果您查看以下记录:
>>> x = "7"
>>> if x > 10:
... print "yes"
...
yes
>>> if int(x) > 10:
... print "yes"
...
>>> x = 7
>>> if x > 10:
... print "yes"
...
>>>
你会明白为什么这不是一个好主意。
您看到这种(您可能称之为奇怪的)行为的原因可以从 manual 中找到。在 5.3
的底部:
CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.
因为"7"
的类型是str
,10
的类型是int
,所以很简单比较类型名称("str"
在字母顺序中总是大于 "int"
),导致一些有趣的事情,例如:
>>> "1" > 99999999999999999999999
True
>>> "1" == 1
False
该实现细节至少在 2.7.2 之前仍然有效。它可能在 Python 3000 流中发生了变化(该子句肯定已从相关文档部分中删除),但 documentation there仍然说:
Most other objects of built-in types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one execution of a program.
所以这可能不是您应该依赖的东西。
关于Python:即使不满足条件,如果仍在运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6421981/