newscheck.py

来自「python web programming 部分」· Python 代码 · 共 55 行

PY
55
字号
import nntplib, cStringIO, rfc822, sys

SRVR = "news.demon.co.uk"           # Your news server
USER ="username"                    # Your account name
PASS = "xyzzy"                      # Your password
newsgroup = "comp.lang.python"      # Group of your choice

news = nntplib.NNTP(SRVR, user=USER, password=PASS)
resp, estimate, first, last, name = news.group(newsgroup)

if estimate == '0':
    print "No messages in ", newsgroup
    sys.exit(-1)

first =  int(first)
last = int(last)

artnum = first # better: cached from the previous run

# establish first available article
while artnum <= last:
    try:
        news.stat(str(artnum))
        break
    except nntplib.NNTPError, err:
        if err.response[:3] != '423':
            raise
        else:
            artnum += 1
else:
    print "No messages available in ", newsgroup
    sys.exit(-2)

# loop through articles, extracting headers
artnum = str(artnum)
count = 0
while count < 10:
    try:
        hdrs = news.head(artnum)[3]
        mesg = rfc822.Message(cStringIO.StringIO("\r\n".join(hdrs)))
        print '%s\n   +++%s' % (mesg.getheader("from"),
                             mesg.getheader("subject"))
        count += 1
    except nntplib.NNTPError:
        pass
    try:
        artnum = news.next()[1]
    except nntplib.NNTPError, err:
        if err.response[:3] != '421':
            raise
        else:
            break
news.quit()

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?