Python:即使不满足条件,如果仍在运行

标签 python gmail

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"的类型是str10的类型是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/

相关文章:

Python:解析由文本表示的长 double 组非常慢

python - 如何通过查看 AST 来区分生成器中的普通 Python 函数?

python - uWSGI 是否在启动时启动所有进程?

php - imap_fetchstructure() 问题 : Bad message number

使用 Gmail 发送 git imap

api - 使用api发送gmail附件失败

python - 元组列表的频率

python - 防止窗口最小化或关闭

Java无法发送带有图像的html电子邮件

api - 通过 API 创建 gmail、facebook 和 twitter 帐户?