当前位置: 首页>>代码示例>>Python>>正文


Python NNTP.body方法代码示例

本文整理汇总了Python中nntplib.NNTP.body方法的典型用法代码示例。如果您正苦于以下问题:Python NNTP.body方法的具体用法?Python NNTP.body怎么用?Python NNTP.body使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在nntplib.NNTP的用法示例。


在下文中一共展示了NNTP.body方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_items

# 需要导入模块: from nntplib import NNTP [as 别名]
# 或者: from nntplib.NNTP import body [as 别名]
 def get_items(self):
     server = NNTP(self.servername)
     resp, count, first, last, name = server.group(self.group)
     start = last - self.howmany + 1
     resp, overviews = server.over((start, last))
     for id, over in overviews:
         title = decode_header(over['subject'])
         resp, info = server.body(id)
         body = '\n'.join(line.decode('latin')
                          for line in info.lines) + '\n\n'
         yield NewsItem(title, body)
     server.quit()
开发者ID:BrandonSherlocking,项目名称:beginning-python-3ed,代码行数:14,代码来源:listing23-2.py

示例2: getItems

# 需要导入模块: from nntplib import NNTP [as 别名]
# 或者: from nntplib.NNTP import body [as 别名]
	def getItems(self):
	#	yesterday = localtime(time()-self.window*day)
	#	date = strftime('%y%m%d',yesterday)
	#	time = strftime('%H%M%S',yesterday)
		# create a nntp server
		s = NNTP(self.servername)	
		resp,count,first,last,name = s.group(self.groupname)
		resp,overviews = s.over((last-1,last))
		for num,over in overviews:
			title = over.get('subject')
			resp,body = s.body(num)
			# create a generator to iterate news 
			if title and body:
				yield NewsItem(title,body)
		s.quit()	
开发者ID:justasabc,项目名称:python_tutorials,代码行数:17,代码来源:newsagent3.py

示例3: localtime

# 需要导入模块: from nntplib import NNTP [as 别名]
# 或者: from nntplib.NNTP import body [as 别名]
#coding=utf-8
#
from nntplib import NNTP
from time import strftime, time, localtime

day = 24 * 60 * 60 # Number of seconds in one day
yesterday = localtime(time() - day)
date = strftime('%y%m%d', yesterday)
hour = strftime('%H%M%S', yesterday)

servername = 'news.mixmin.net'
group = 'talk.euthanasia'
server = NNTP(servername)
ids = server.newnews(group, date, hour)[1]

for id in ids:
    head = server.head(id)[3]
    for line in head:
        if line.lower().startswith('subject:'):
            subject = line[9:]
            break

    body = server.body(id)[3]
    print subject 
    print '-'*len(subject)
    print '\n'.join(body)

server.quit()
开发者ID:ruanima,项目名称:TenTinyPythonProject,代码行数:30,代码来源:newsagent1.py

示例4: NNTP

# 需要导入模块: from nntplib import NNTP [as 别名]
# 或者: from nntplib.NNTP import body [as 别名]
except:
    servername = 'news.gmane.org'
    groupname  = 'gmane.comp.python.general'          # cmd line args or defaults
    showcount  = 10                          # show last showcount posts

# connect to nntp server
print 'Connecting to', servername, 'for', groupname
from nntplib import NNTP
connection = NNTP(servername)
(reply, count, first, last, name) = connection.group(groupname)
print '%s has %s articles: %s-%s' % (name, count, first, last)

# get request headers only
fetchfrom = str(int(last) - (showcount-1))
(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 raw_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 raw_input('=> Show body?') in ['y', 'Y']:
            reply, num, tid, list = connection.body(id)
            for line in list:
                print line[:80]
    print
print connection.quit( )
开发者ID:wintergalt,项目名称:canilla,代码行数:33,代码来源:code_idol.py

示例5: NNTP

# 需要导入模块: from nntplib import NNTP [as 别名]
# 或者: from nntplib.NNTP import body [as 别名]
from nntplib import NNTP

servername = 'news.foo.bar'
group = 'comp.lang.python.announce'
server = NNTP(servername)
howmany = 10

resp, count, first, last, name = server.group(group)

start = last - howmany + 1

resp, overviews = server.over((start, last))

for id, over in overviews:
    subject = over['subject']
    resp, info = server.body(id)
    print(subject)
    print('-' * len(subject))
    for line in info.lines:
        print(line.decode('latin1'))
    print()

server.quit()
开发者ID:BrandonSherlocking,项目名称:beginning-python-3ed,代码行数:25,代码来源:listing23-1.py

示例6: Archive

# 需要导入模块: from nntplib import NNTP [as 别名]
# 或者: from nntplib.NNTP import body [as 别名]
class Archive(object):

    @staticmethod
    def is_diff(body):
        return bool([line for line in body if line.startswith("diff ")])

    def __init__(self, group, server):
        self.conn = NNTP(server)
        resp, count, first, last, name = self.conn.group(group)

        self.group = group
        self.server = server
        self.first = int(first)
        self.last = int(last)

    def get_number_from_user(self, msg_id):
        """
            Convert something the user might input into a message id.

            These are:
            # An NNTP message number
            # A gmane link that includes the NNTP message number
            # The original Message-Id header of the message.

            NOTE: gmane's doesn't include the message number in STAT requests
            that involve only the Message-Id (hence the convolution of getting
            all the headers).
        """
        msg_id = re.sub(r".*gmane.org/gmane.comp.version-control.git/([0-9]+).*", r"\1", str(msg_id))
        _, n, id, result = self.conn.head(msg_id)

        for header in result:
            m = re.match(r"Xref: .*:([0-9]+)\s*$", header, re.I)
            if m:
                return int(m.group(1))
        else:
            raise FatalError("No (or bad) Xref header for message '%s'" % msg_id)

    def get_patch_series(self, user_input, search_limit=100):
        """
            Given an NNTP message number or a Message-Id header return
            an mbox containing the patches introduced by the author of that message.

            This handles the case where the threading is right *and* the patches
            are numbered in a simple scheme:

            [PATCH] this patch has no replies and stands on its own

            [PATCH 0/2] this is an introduction to the series
              |- [PATCH 1/2] the first commit
              |- [PATCH 2/2] the second commit

            [PATCH 1/3] this is the first commit
              |- [PATCH 2/3] and this is the second
                   |- [PATCH 3/3] and this is the third

            TODO: it would be nice to make the search more efficient, we can
            use the numbers in [PATCH <foo>/<bar>] to stop early.
        """

        start_id = self.get_number_from_user(user_input)

        messages = limit(self.messages_starting_from(start_id), search_limit)
        try:
            thread = Thread(messages.next())
        except StopIteration:
            raise FatalError("No message at id '%s' using XOVER")

        n_since_last = 0
        for message in messages:
            if n_since_last > 5:
                break

            elif thread.should_include(message):
                n_since_last = 0
                thread.append(message)

            else:
                n_since_last += 1

        else:
            raise FatalError('did not find end of series within %s messages', search_limit)

        for message in self.xover(start_id - 5, start_id -1):
            if thread.should_include(message):
                thread.append(message)

        return self.mboxify(thread)

    def mboxify(self, thread):
        """
            Convert a thread into an mbox for application via git-am.
        """
        lines = []

        for message in thread.in_order():
            _, number, msg_id, body = self.conn.body(str(message.number))

            # git-am doesn't like empty patches very much, and the 0/X'th patch is
            # often not a patch, we skip it here. (TODO, warn the user about this)
#.........这里部分代码省略.........
开发者ID:ConradIrwin,项目名称:git-fetch-series,代码行数:103,代码来源:git-fetch-series.py

示例7: print

# 需要导入模块: from nntplib import NNTP [as 别名]
# 或者: from nntplib.NNTP import body [as 别名]
resp,num,msg_id = s.stat(last)
print(num,msg_id)

# article
'Return a tuple (response, info) where info is a namedtuple with three attributes number, message_id and lines (in that order).'
print('-'*10)
resp,info = s.article(last)
print(info.number,info.message_id,len(info.lines))

# head
'Same as article(), but sends a HEAD command. The lines returned (or written to file) will only contain the message headers, not the body.'
print('-'*10)
resp,info = s.head(last)
print(info.number,info.message_id,len(info.lines))

# body
'Same as article(), but sends a BODY command. The lines returned (or written to file) will only contain the message body, not the headers.'
print('-'*10)
resp,info = s.body(last)
print(info.number,info.message_id,len(info.lines))

# newgroups
'Return a pair (response, groups) where groups is a list of group names that are new since the given date and time'
#resp,groups = s.newgroups(date,time)
#print len(groups)
#pprint(groups)

#newnews
'Return a pair (response, articles) where articles is a list of message idsThis command is frequently disabled by NNTP server administrators.'
#resp,ids = s.newnews(groupname,date,time)
开发者ID:justasabc,项目名称:python_tutorials,代码行数:32,代码来源:newsagent.py

示例8: localtime

# 需要导入模块: from nntplib import NNTP [as 别名]
# 或者: from nntplib.NNTP import body [as 别名]
window = 7
yesterday = localtime(time()-window*day)
date = strftime('%y%m%d',yesterday)
time = strftime('%H%M%S',yesterday)

servername = 'news.gmane.org'
groupname = 'gmane.comp.python.apple'
s = NNTP(servername)

resp,count,first,last,name = s.group(groupname)

resp,overviews = s.over((last-1,last))
for num,over in overviews:
	print(num)# 1-100
	# print(over.keys())
	# ['xref', 'from', ':lines', ':bytes', 'references', 'date', 'message-id', 'subject']
	'''
	resp,h = s.head(num)
	for line in h.lines:
		print(type(line)) # bytes
		print(line)
	'''
	resp,b = s.body(num)
	sj = over.get('subject')
	dt = over.get('date')
	print(dt)
	print(sj)
	print('-'*len(sj))
	#pprint(b)

开发者ID:justasabc,项目名称:python_tutorials,代码行数:31,代码来源:newsagent2.py

示例9: Client

# 需要导入模块: from nntplib import NNTP [as 别名]
# 或者: from nntplib.NNTP import body [as 别名]
class Client(Context):
    def __init__(self, log,
    hostname, port=None, username=None, password=None, *,
    debuglevel=None, **timeout):
        self.log = log
        self.hostname = hostname
        self.port = port
        self.username = username
        self.password = password
        self.debuglevel = debuglevel
        self.timeout = timeout
        Context.__init__(self)
        self.connect()
    
    def connect(self):
        address = net.format_addr((self.hostname, self.port))
        self.log.write("Connecting to {}\n".format(address))
        if self.port is None:
            port = ()
        else:
            port = (self.port,)
        self.connect_time = time.monotonic()
        self.nntp = NNTP(self.hostname, *port, **self.timeout)
        with ExitStack() as cleanup:
            cleanup.push(self)
            if self.debuglevel is not None:
                self.nntp.set_debuglevel(self.debuglevel)
            self.log.write("{}\n".format(self.nntp.getwelcome()))
            
            if self.username is not None:
                self.log.write("Logging in as {}\n".format(self.username))
                with self.handle_abort():
                    self.nntp.login(self.username, self.password)
                self.log.write("Logged in\n")
            cleanup.pop_all()
    
    def body(self, id, *pos, **kw):
        id = "<{}>".format(id)
        retry = 0
        while True:
            try:
                with self.handle_abort():
                    self.nntp.body(id, *pos, **kw)
                break
            except failure_responses as err:
                [code, *msg] = err.response.split(maxsplit=1)
                if code == "400":
                    [msg] = msg or (None,)
                    if not msg:
                        msg = "Server shut down connection"
                elif code[1] == "0" and not retry:
                    msg = err.response
                else:
                    raise
            self.log.write(msg + "\n")
            self.log_time()
            if retry >= 60:
                raise TimeoutError()
            self.close()
            time.sleep(retry)
            if not retry:
                start = time.monotonic()
            self.connect()
            if retry:
                retry *= 2
            else:
                retry = time.monotonic() - start
                if retry <= 0:
                    retry = 0.5
    
    def group(self, *pos, **kw):
        with self.handle_abort():
            return self.nntp.group(*pos, **kw)
    def over(self, *pos, **kw):
        with self.handle_abort():
            return self.nntp.over(*pos, **kw)
    def hdr(self, *pos, **kw):
        with self.handle_abort():
            return self.nntp.xhdr(*pos, **kw)
    
    @contextmanager
    def handle_abort(self):
        try:
            yield
        except failure_responses:
            raise  # NNTP connection still intact
        except:
            # Protocol is disrupted so abort the connection straight away
            self.close()
            raise
    
    def close(self):
        if not self.nntp:
            return
        
        # Ignore failure of inappropriate QUIT command
        with suppress(NNTPError), self.nntp:
            pass
        self.nntp = None
    
#.........这里部分代码省略.........
开发者ID:vadmium,项目名称:usenet-downloader,代码行数:103,代码来源:nntp.py

示例10: DownloadSpots

# 需要导入模块: from nntplib import NNTP [as 别名]
# 或者: from nntplib.NNTP import body [as 别名]

#.........这里部分代码省略.........
                - image: the location of the image file: url or nntp id
                - website: url of the website
                - desc: a description of the spot
                - title2: the title of the spot
                  (is called title2 to avoid a conflict)
        '''

        id = str(id)
        self.news.group('free.pt')
        print id
        head = self.news.head(id)[-1]
        xmltext = ''.join(item[7:] for item in head if
                          item.startswith('X-XML:'))
        xml = etree.XML(xmltext)
        xmldict = defaultdict(list)

        xmldict['nzb'] = [i.text for i in xml.find('.//NZB').iter('Segment')]

        imgfind = xml.find('.//Image')
        if imgfind is not None:
            if imgfind.find('.//Segment') is not None:
                xmldict['image'] = imgfind.find('.//Segment').text
            else:
                xmldict['image'] = imgfind.text
        else:
            xmldict['image'] = None

        webfind = xml.find('.//Website')
        if webfind is not None:
            xmldict['website'] = webfind.text
        else:
            xmldict['website'] = None

        xmldict['desc'] = bb2html('\n'.join(self.news.body(id)[-1]))

        xmldict['title2'] = xml.find('.//Title').text
        print xmldict
        return xmldict

    def download_image(self, article, imgnr):
        '''Download and save an image file.
        
        Args:
            article: Location of the file, can be:
                - None
                - an url: 'http://url.to.image.ext'
                - a nntp id: '[email protected]'
            imgnr: filename of the saved image
        '''
        print imgnr
        file = 'temp/%s.picture' % imgnr
        if article is None:
            shutil.copy('none.png', file)
        elif article.startswith('http'):
            if 'imgchili.com' in article:
                article = re.sub(r't([0-9]\.imgchili)', r'i\1', article)
            try:
                print urllib.urlretrieve(article, file)
            except:
                print 'Image download error'
                shutil.copy('none.png', file)
        elif '@' in article:
            article = '<%s>' % article
            print article
            try:
                self.news.group('alt.binaries.ftd')
开发者ID:BartLH,项目名称:PySpotQt,代码行数:70,代码来源:download_spots.py


注:本文中的nntplib.NNTP.body方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。