⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 nntplib.py

📁 mallet是自然语言处理、机器学习领域的一个开源项目。
💻 PY
📖 第 1 页 / 共 2 页
字号:
"""An NNTP client class based on RFC 977: Network News Transfer Protocol.Example:>>> from nntplib import NNTP>>> s = NNTP('news')>>> resp, count, first, last, name = s.group('comp.lang.python')>>> print 'Group', name, 'has', count, 'articles, range', first, 'to', lastGroup comp.lang.python has 51 articles, range 5770 to 5821>>> resp, subs = s.xhdr('subject', first + '-' + last)>>> resp = s.quit()>>>Here 'resp' is the server response line.Error responses are turned into exceptions.To post an article from a file:>>> f = open(filename, 'r') # file containing article, including header>>> resp = s.post(f)>>>For descriptions of all methods, read the comments in the code below.Note that all arguments and return values representing article numbersare strings, not numbers, since they are rarely used for calculations."""# RFC 977 by Brian Kantor and Phil Lapsley.# xover, xgtitle, xpath, date methods by Kevan Heydon# Importsimport reimport socketimport types__all__ = ["NNTP","NNTPReplyError","NNTPTemporaryError",           "NNTPPermanentError","NNTPProtocolError","NNTPDataError",           "error_reply","error_temp","error_perm","error_proto",           "error_data",]# Exceptions raised when an error or invalid response is receivedclass NNTPError(Exception):    """Base class for all nntplib exceptions"""    def __init__(self, *args):        apply(Exception.__init__, (self,)+args)        try:            self.response = args[0]        except IndexError:            self.response = 'No response given'class NNTPReplyError(NNTPError):    """Unexpected [123]xx reply"""    passclass NNTPTemporaryError(NNTPError):    """4xx errors"""    passclass NNTPPermanentError(NNTPError):    """5xx errors"""    passclass NNTPProtocolError(NNTPError):    """Response does not begin with [1-5]"""    passclass NNTPDataError(NNTPError):    """Error in response data"""    pass# for backwards compatibilityerror_reply = NNTPReplyErrorerror_temp = NNTPTemporaryErrorerror_perm = NNTPPermanentErrorerror_proto = NNTPProtocolErrorerror_data = NNTPDataError# Standard port used by NNTP serversNNTP_PORT = 119# Response numbers that are followed by additional text (e.g. article)LONGRESP = ['100', '215', '220', '221', '222', '224', '230', '231', '282']# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)CRLF = '\r\n'# The class itselfclass NNTP:    def __init__(self, host, port=NNTP_PORT, user=None, password=None,                 readermode=None):        """Initialize an instance.  Arguments:        - host: hostname to connect to        - port: port to connect to (default the standard NNTP port)        - user: username to authenticate with        - password: password to use with username        - readermode: if true, send 'mode reader' command after                      connecting.        readermode is sometimes necessary if you are connecting to an        NNTP server on the local machine and intend to call        reader-specific comamnds, such as `group'.  If you get        unexpected NNTPPermanentErrors, you might need to set        readermode.        """        self.host = host        self.port = port        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)        self.sock.connect((self.host, self.port))        self.file = self.sock.makefile('rb')        self.debugging = 0        self.welcome = self.getresp()        # 'mode reader' is sometimes necessary to enable 'reader' mode.        # However, the order in which 'mode reader' and 'authinfo' need to        # arrive differs between some NNTP servers. Try to send        # 'mode reader', and if it fails with an authorization failed        # error, try again after sending authinfo.        readermode_afterauth = 0        if readermode:            try:                self.welcome = self.shortcmd('mode reader')            except NNTPPermanentError:                # error 500, probably 'not implemented'                pass            except NNTPTemporaryError, e:                if user and e.response[:3] == '480':                    # Need authorization before 'mode reader'                    readermode_afterauth = 1                else:                    raise        if user:            resp = self.shortcmd('authinfo user '+user)            if resp[:3] == '381':                if not password:                    raise NNTPReplyError(resp)                else:                    resp = self.shortcmd(                            'authinfo pass '+password)                    if resp[:3] != '281':                        raise NNTPPermanentError(resp)            if readermode_afterauth:                try:                    self.welcome = self.shortcmd('mode reader')                except NNTPPermanentError:                    # error 500, probably 'not implemented'                    pass    # Get the welcome message from the server    # (this is read and squirreled away by __init__()).    # If the response code is 200, posting is allowed;    # if it 201, posting is not allowed    def getwelcome(self):        """Get the welcome message from the server        (this is read and squirreled away by __init__()).        If the response code is 200, posting is allowed;        if it 201, posting is not allowed."""        if self.debugging: print '*welcome*', `self.welcome`        return self.welcome    def set_debuglevel(self, level):        """Set the debugging level.  Argument 'level' means:        0: no debugging output (default)        1: print commands and responses but not body text etc.        2: also print raw lines read and sent before stripping CR/LF"""        self.debugging = level    debug = set_debuglevel    def putline(self, line):        """Internal: send one line to the server, appending CRLF."""        line = line + CRLF        if self.debugging > 1: print '*put*', `line`        self.sock.sendall(line)    def putcmd(self, line):        """Internal: send one command to the server (through putline())."""        if self.debugging: print '*cmd*', `line`        self.putline(line)    def getline(self):        """Internal: return one line from the server, stripping CRLF.        Raise EOFError if the connection is closed."""        line = self.file.readline()        if self.debugging > 1:            print '*get*', `line`        if not line: raise EOFError        if line[-2:] == CRLF: line = line[:-2]        elif line[-1:] in CRLF: line = line[:-1]        return line    def getresp(self):        """Internal: get a response from the server.        Raise various errors if the response indicates an error."""        resp = self.getline()        if self.debugging: print '*resp*', `resp`        c = resp[:1]        if c == '4':            raise NNTPTemporaryError(resp)        if c == '5':            raise NNTPPermanentError(resp)        if c not in '123':            raise NNTPProtocolError(resp)        return resp    def getlongresp(self, file=None):        """Internal: get a response plus following text from the server.        Raise various errors if the response indicates an error."""        openedFile = None        try:            # If a string was passed then open a file with that name            if isinstance(file, types.StringType):                openedFile = file = open(file, "w")            resp = self.getresp()            if resp[:3] not in LONGRESP:                raise NNTPReplyError(resp)            list = []            while 1:                line = self.getline()                if line == '.':                    break                if line[:2] == '..':                    line = line[1:]                if file:                    file.write(line + "\n")                else:                    list.append(line)        finally:            # If this method created the file, then it must close it            if openedFile:                openedFile.close()        return resp, list    def shortcmd(self, line):        """Internal: send a command and get the response."""        self.putcmd(line)        return self.getresp()    def longcmd(self, line, file=None):        """Internal: send a command and get the response plus following text."""        self.putcmd(line)        return self.getlongresp(file)    def newgroups(self, date, time):        """Process a NEWGROUPS command.  Arguments:        - date: string 'yymmdd' indicating the date        - time: string 'hhmmss' indicating the time        Return:        - resp: server response if successful        - list: list of newsgroup names"""        return self.longcmd('NEWGROUPS ' + date + ' ' + time)    def newnews(self, group, date, time):        """Process a NEWNEWS command.  Arguments:        - group: group name or '*'        - date: string 'yymmdd' indicating the date        - time: string 'hhmmss' indicating the time        Return:        - resp: server response if successful        - list: list of article ids"""        cmd = 'NEWNEWS ' + group + ' ' + date + ' ' + time        return self.longcmd(cmd)    def list(self):        """Process a LIST command.  Return:        - resp: server response if successful        - list: list of (group, last, first, flag) (strings)"""        resp, list = self.longcmd('LIST')        for i in range(len(list)):            # Parse lines into "group last first flag"            list[i] = tuple(list[i].split())        return resp, list    def group(self, name):

⌨️ 快捷键说明

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