(reply, subjects) = connection.xhdr('subject', (fetchfrom + '-' + last))
show headers, get message hdr+body
for (id, subj) in subjects: # [-showcount:] if fetch all hdrs
print('Article %s [%s]' % (id, subj))
if not listonly and input('=> Display?') in ['y', 'Y']:
reply, num, tid, list = connection.head(id)
for line in list:
for prefix in showhdrs:
if line[:len(prefix)] == prefix:
print(line[:80])
break
if input('=> Show body?') in ['y', 'Y']:
reply, num, tid, list = connection.body(id)
for line in list:
print(line[:80])
print()
print(connection.quit())
As for FTP and email tools, the script creates an NNTP object and calls its methods to
fetch newsgroup information and articles’ header and body text. The xhdr method, for
example, loads selected headers from a range of messages.
For NNTP servers that require authentication, you may also have to pass a username,
a password, and possibly a reader-mode flag to the NNTP call. See the Python Library
manual for more on other NNTP parameters and object methods.
In the interest of space and time, I’ll omit this script’s outputs here. When run, it
connects to the server and displays each article’s subject line, pausing to ask whether
it should fetch and show the article’s header information lines (headers listed in the
variable showhdrs only) and body text. We can also pass this script an explicit server
name, newsgroup, and display count on the command line to apply it in different ways.
With a little more work, we could turn this script into a full-blown news interface. For
instance, new articles could be posted from within a Python script with code of this
form (assuming the local file already contains proper NNTP header lines):
# to post, say this (but only if you really want to post!)
connection = NNTP(servername)
localfile = open('filename') # file has proper headers
connection.post(localfile) # send text to newsgroup
connection.quit()
We might also add a tkinter-based GUI frontend to this script to make it more usable,
but we’ll leave such an extension on the suggested exercise heap (see also the PyMail-
GUI interface’s suggested extensions at the end of the next chapter—email and news
messages have a similar structure).
NNTP: Accessing Newsgroups | 993