desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Constructor for the GzipFile class. At least one of fileobj and filename must be given a non-trivial value. The new class instance is based on fileobj, which can be a regular file, an io.BytesIO object, or any other object which simulates a file. It defaults to None, in which case filename is opened to provide a file ...
def __init__(self, filename=None, mode=None, compresslevel=9, fileobj=None, mtime=None):
if (mode and (('t' in mode) or ('U' in mode))): raise ValueError('Invalid mode: {!r}'.format(mode)) if (mode and ('b' not in mode)): mode += 'b' if (fileobj is None): fileobj = self.myfileobj = builtins.open(filename, (mode or 'rb')) if (filename is None): filename ...
'Raises a ValueError if the underlying file object has been closed.'
def _check_closed(self):
if self.closed: raise ValueError('I/O operation on closed file.')
'Invoke the underlying file object\'s fileno() method. This will raise AttributeError if the underlying file object doesn\'t support fileno().'
def fileno(self):
return self.fileobj.fileno()
'Return the uncompressed stream file position indicator to the beginning of the file'
def rewind(self):
if (self.mode != READ): raise OSError("Can't rewind in write mode") self.fileobj.seek(0) self._new_member = True self.extrabuf = '' self.extrasize = 0 self.extrastart = 0 self.offset = 0
'Push a token onto the stack popped by the get_token method'
def push_token(self, tok):
if (self.debug >= 1): print ('shlex: pushing token ' + repr(tok)) self.pushback.appendleft(tok)
'Push an input source onto the lexer\'s input source stack.'
def push_source(self, newstream, newfile=None):
if isinstance(newstream, str): newstream = StringIO(newstream) self.filestack.appendleft((self.infile, self.instream, self.lineno)) self.infile = newfile self.instream = newstream self.lineno = 1 if self.debug: if (newfile is not None): print ('shlex: pushing to...
'Pop the input source stack.'
def pop_source(self):
self.instream.close() (self.infile, self.instream, self.lineno) = self.filestack.popleft() if self.debug: print ('shlex: popping to %s, line %d' % (self.instream, self.lineno)) self.state = ' '
'Get a token from the input stream (or from stack if it\'s nonempty)'
def get_token(self):
if self.pushback: tok = self.pushback.popleft() if (self.debug >= 1): print ('shlex: popping token ' + repr(tok)) return tok raw = self.read_token() if (self.source is not None): while (raw == self.source): spec = self.sourcehook(self.read_tok...
'Hook called on a filename to be sourced.'
def sourcehook(self, newfile):
if (newfile[0] == '"'): newfile = newfile[1:(-1)] if (isinstance(self.infile, str) and (not os.path.isabs(newfile))): newfile = os.path.join(os.path.dirname(self.infile), newfile) return (newfile, open(newfile, 'r'))
'Emit a C-compiler-like, Emacs-friendly error-message leader.'
def error_leader(self, infile=None, lineno=None):
if (infile is None): infile = self.infile if (lineno is None): lineno = self.lineno return ('"%s", line %d: ' % (infile, lineno))
'Return true if the scope uses exec. Deprecated method.'
def has_exec(self):
return False
'Return true if the scope uses import *'
def has_import_star(self):
return bool((self._table.optimized & OPT_IMPORT_STAR))
'Returns true if name binding introduces new namespace. If the name is used as the target of a function or class statement, this will be true. Note that a single name can be bound to multiple objects. If is_namespace() is true, the name may also be bound to other objects, like an int or list, that does not introduce a...
def is_namespace(self):
return bool(self.__namespaces)
'Return a list of namespaces bound to this name'
def get_namespaces(self):
return self.__namespaces
'Returns the single namespace bound to this name. Raises ValueError if the name is bound to multiple namespaces.'
def get_namespace(self):
if (len(self.__namespaces) != 1): raise ValueError('name is bound to multiple namespaces') return self.__namespaces[0]
'Template() returns a fresh pipeline template.'
def __init__(self):
self.debugging = 0 self.reset()
't.__repr__() implements repr(t).'
def __repr__(self):
return ('<Template instance, steps=%r>' % (self.steps,))
't.reset() restores a pipeline template to its initial state.'
def reset(self):
self.steps = []
't.clone() returns a new pipeline template with identical initial state as the current one.'
def clone(self):
t = Template() t.steps = self.steps[:] t.debugging = self.debugging return t
't.debug(flag) turns debugging on or off.'
def debug(self, flag):
self.debugging = flag
't.append(cmd, kind) adds a new step at the end.'
def append(self, cmd, kind):
if (type(cmd) is not type('')): raise TypeError('Template.append: cmd must be a string') if (kind not in stepkinds): raise ValueError(('Template.append: bad kind %r' % (kind,))) if (kind == SOURCE): raise ValueError('Template.append: SOURCE can only ...
't.prepend(cmd, kind) adds a new step at the front.'
def prepend(self, cmd, kind):
if (type(cmd) is not type('')): raise TypeError('Template.prepend: cmd must be a string') if (kind not in stepkinds): raise ValueError(('Template.prepend: bad kind %r' % (kind,))) if (kind == SINK): raise ValueError('Template.prepend: SINK can only ...
't.open(file, rw) returns a pipe or file object open for reading or writing; the file is the other end of the pipeline.'
def open(self, file, rw):
if (rw == 'r'): return self.open_r(file) if (rw == 'w'): return self.open_w(file) raise ValueError(("Template.open: rw must be 'r' or 'w', not %r" % (rw,)))
't.open_r(file) and t.open_w(file) implement t.open(file, \'r\') and t.open(file, \'w\') respectively.'
def open_r(self, file):
if (not self.steps): return open(file, 'r') if (self.steps[(-1)][1] == SINK): raise ValueError('Template.open_r: pipeline ends width SINK') cmd = self.makepipeline(file, '') return os.popen(cmd, 'r')
'Setup connection to remote server on "host:port" (default: localhost:standard IMAP4 port). This connection will be used by the routines: read, readline, send, shutdown.'
def open(self, host='', port=IMAP4_PORT):
self.host = host self.port = port self.sock = self._create_socket() self.file = self.sock.makefile('rb')
'Read \'size\' bytes from remote.'
def read(self, size):
return self.file.read(size)
'Read line from remote.'
def readline(self):
line = self.file.readline((_MAXLINE + 1)) if (len(line) > _MAXLINE): raise self.error(('got more than %d bytes' % _MAXLINE)) return line
'Send data to remote.'
def send(self, data):
self.sock.sendall(data)
'Close I/O established in "open".'
def shutdown(self):
self.file.close() try: self.sock.shutdown(socket.SHUT_RDWR) except OSError as e: if (e.errno != errno.ENOTCONN): raise finally: self.sock.close()
'Return socket instance used to connect to IMAP4 server. socket = <instance>.socket()'
def socket(self):
return self.sock
'Return most recent \'RECENT\' responses if any exist, else prompt server for an update using the \'NOOP\' command. (typ, [data]) = <instance>.recent() \'data\' is None if no new messages, else list of RECENT responses, most recent last.'
def recent(self):
name = 'RECENT' (typ, dat) = self._untagged_response('OK', [None], name) if dat[(-1)]: return (typ, dat) (typ, dat) = self.noop() return self._untagged_response(typ, dat, name)
'Return data for response \'code\' if received, or None. Old value for response \'code\' is cleared. (code, [data]) = <instance>.response(code)'
def response(self, code):
return self._untagged_response(code, [None], code.upper())
'Append message to named mailbox. (typ, [data]) = <instance>.append(mailbox, flags, date_time, message) All args except `message\' can be None.'
def append(self, mailbox, flags, date_time, message):
name = 'APPEND' if (not mailbox): mailbox = 'INBOX' if flags: if ((flags[0], flags[(-1)]) != ('(', ')')): flags = ('(%s)' % flags) else: flags = None if date_time: date_time = Time2Internaldate(date_time) else: date_time = None self.literal...
'Authenticate command - requires response processing. \'mechanism\' specifies which authentication mechanism is to be used - it must appear in <instance>.capabilities in the form AUTH=<mechanism>. \'authobject\' must be a callable object: data = authobject(response) It will be called to process server continuation resp...
def authenticate(self, mechanism, authobject):
mech = mechanism.upper() self.literal = _Authenticator(authobject).process (typ, dat) = self._simple_command('AUTHENTICATE', mech) if (typ != 'OK'): raise self.error(dat[(-1)]) self.state = 'AUTH' return (typ, dat)
'(typ, [data]) = <instance>.capability() Fetch capabilities list from server.'
def capability(self):
name = 'CAPABILITY' (typ, dat) = self._simple_command(name) return self._untagged_response(typ, dat, name)
'Checkpoint mailbox on server. (typ, [data]) = <instance>.check()'
def check(self):
return self._simple_command('CHECK')
'Close currently selected mailbox. Deleted messages are removed from writable mailbox. This is the recommended command before \'LOGOUT\'. (typ, [data]) = <instance>.close()'
def close(self):
try: (typ, dat) = self._simple_command('CLOSE') finally: self.state = 'AUTH' return (typ, dat)
'Copy \'message_set\' messages onto end of \'new_mailbox\'. (typ, [data]) = <instance>.copy(message_set, new_mailbox)'
def copy(self, message_set, new_mailbox):
return self._simple_command('COPY', message_set, new_mailbox)
'Create new mailbox. (typ, [data]) = <instance>.create(mailbox)'
def create(self, mailbox):
return self._simple_command('CREATE', mailbox)
'Delete old mailbox. (typ, [data]) = <instance>.delete(mailbox)'
def delete(self, mailbox):
return self._simple_command('DELETE', mailbox)
'Delete the ACLs (remove any rights) set for who on mailbox. (typ, [data]) = <instance>.deleteacl(mailbox, who)'
def deleteacl(self, mailbox, who):
return self._simple_command('DELETEACL', mailbox, who)
'Permanently remove deleted items from selected mailbox. Generates \'EXPUNGE\' response for each deleted message. (typ, [data]) = <instance>.expunge() \'data\' is list of \'EXPUNGE\'d message numbers in order received.'
def expunge(self):
name = 'EXPUNGE' (typ, dat) = self._simple_command(name) return self._untagged_response(typ, dat, name)
'Fetch (parts of) messages. (typ, [data, ...]) = <instance>.fetch(message_set, message_parts) \'message_parts\' should be a string of selected parts enclosed in parentheses, eg: "(UID BODY[TEXT])". \'data\' are tuples of message part envelope and data.'
def fetch(self, message_set, message_parts):
name = 'FETCH' (typ, dat) = self._simple_command(name, message_set, message_parts) return self._untagged_response(typ, dat, name)
'Get the ACLs for a mailbox. (typ, [data]) = <instance>.getacl(mailbox)'
def getacl(self, mailbox):
(typ, dat) = self._simple_command('GETACL', mailbox) return self._untagged_response(typ, dat, 'ACL')
'(typ, [data]) = <instance>.getannotation(mailbox, entry, attribute) Retrieve ANNOTATIONs.'
def getannotation(self, mailbox, entry, attribute):
(typ, dat) = self._simple_command('GETANNOTATION', mailbox, entry, attribute) return self._untagged_response(typ, dat, 'ANNOTATION')
'Get the quota root\'s resource usage and limits. Part of the IMAP4 QUOTA extension defined in rfc2087. (typ, [data]) = <instance>.getquota(root)'
def getquota(self, root):
(typ, dat) = self._simple_command('GETQUOTA', root) return self._untagged_response(typ, dat, 'QUOTA')
'Get the list of quota roots for the named mailbox. (typ, [[QUOTAROOT responses...], [QUOTA responses]]) = <instance>.getquotaroot(mailbox)'
def getquotaroot(self, mailbox):
(typ, dat) = self._simple_command('GETQUOTAROOT', mailbox) (typ, quota) = self._untagged_response(typ, dat, 'QUOTA') (typ, quotaroot) = self._untagged_response(typ, dat, 'QUOTAROOT') return (typ, [quotaroot, quota])
'List mailbox names in directory matching pattern. (typ, [data]) = <instance>.list(directory=\'""\', pattern=\'*\') \'data\' is list of LIST responses.'
def list(self, directory='""', pattern='*'):
name = 'LIST' (typ, dat) = self._simple_command(name, directory, pattern) return self._untagged_response(typ, dat, name)
'Identify client using plaintext password. (typ, [data]) = <instance>.login(user, password) NB: \'password\' will be quoted.'
def login(self, user, password):
(typ, dat) = self._simple_command('LOGIN', user, self._quote(password)) if (typ != 'OK'): raise self.error(dat[(-1)]) self.state = 'AUTH' return (typ, dat)
'Force use of CRAM-MD5 authentication. (typ, [data]) = <instance>.login_cram_md5(user, password)'
def login_cram_md5(self, user, password):
(self.user, self.password) = (user, password) return self.authenticate('CRAM-MD5', self._CRAM_MD5_AUTH)
'Authobject to use with CRAM-MD5 authentication.'
def _CRAM_MD5_AUTH(self, challenge):
import hmac pwd = (self.password.encode('ASCII') if isinstance(self.password, str) else self.password) return ((self.user + ' ') + hmac.HMAC(pwd, challenge, 'md5').hexdigest())
'Shutdown connection to server. (typ, [data]) = <instance>.logout() Returns server \'BYE\' response.'
def logout(self):
self.state = 'LOGOUT' try: (typ, dat) = self._simple_command('LOGOUT') except: (typ, dat) = ('NO', [('%s: %s' % sys.exc_info()[:2])]) self.shutdown() if ('BYE' in self.untagged_responses): return ('BYE', self.untagged_responses['BYE']) return (typ, dat)
'List \'subscribed\' mailbox names in directory matching pattern. (typ, [data, ...]) = <instance>.lsub(directory=\'""\', pattern=\'*\') \'data\' are tuples of message part envelope and data.'
def lsub(self, directory='""', pattern='*'):
name = 'LSUB' (typ, dat) = self._simple_command(name, directory, pattern) return self._untagged_response(typ, dat, name)
'Show my ACLs for a mailbox (i.e. the rights that I have on mailbox). (typ, [data]) = <instance>.myrights(mailbox)'
def myrights(self, mailbox):
(typ, dat) = self._simple_command('MYRIGHTS', mailbox) return self._untagged_response(typ, dat, 'MYRIGHTS')
'Returns IMAP namespaces ala rfc2342 (typ, [data, ...]) = <instance>.namespace()'
def namespace(self):
name = 'NAMESPACE' (typ, dat) = self._simple_command(name) return self._untagged_response(typ, dat, name)
'Send NOOP command. (typ, [data]) = <instance>.noop()'
def noop(self):
if __debug__: if (self.debug >= 3): self._dump_ur(self.untagged_responses) return self._simple_command('NOOP')
'Fetch truncated part of a message. (typ, [data, ...]) = <instance>.partial(message_num, message_part, start, length) \'data\' is tuple of message part envelope and data.'
def partial(self, message_num, message_part, start, length):
name = 'PARTIAL' (typ, dat) = self._simple_command(name, message_num, message_part, start, length) return self._untagged_response(typ, dat, 'FETCH')
'Assume authentication as "user". Allows an authorised administrator to proxy into any user\'s mailbox. (typ, [data]) = <instance>.proxyauth(user)'
def proxyauth(self, user):
name = 'PROXYAUTH' return self._simple_command('PROXYAUTH', user)
'Rename old mailbox name to new. (typ, [data]) = <instance>.rename(oldmailbox, newmailbox)'
def rename(self, oldmailbox, newmailbox):
return self._simple_command('RENAME', oldmailbox, newmailbox)
'Search mailbox for matching messages. (typ, [data]) = <instance>.search(charset, criterion, ...) \'data\' is space separated list of matching message numbers.'
def search(self, charset, *criteria):
name = 'SEARCH' if charset: (typ, dat) = self._simple_command(name, 'CHARSET', charset, *criteria) else: (typ, dat) = self._simple_command(name, *criteria) return self._untagged_response(typ, dat, name)
'Select a mailbox. Flush all untagged responses. (typ, [data]) = <instance>.select(mailbox=\'INBOX\', readonly=False) \'data\' is count of messages in mailbox (\'EXISTS\' response). Mandated responses are (\'FLAGS\', \'EXISTS\', \'RECENT\', \'UIDVALIDITY\'), so other responses should be obtained via <instance>.response...
def select(self, mailbox='INBOX', readonly=False):
self.untagged_responses = {} self.is_readonly = readonly if readonly: name = 'EXAMINE' else: name = 'SELECT' (typ, dat) = self._simple_command(name, mailbox) if (typ != 'OK'): self.state = 'AUTH' return (typ, dat) self.state = 'SELECTED' if (('READ-ONLY' i...
'Set a mailbox acl. (typ, [data]) = <instance>.setacl(mailbox, who, what)'
def setacl(self, mailbox, who, what):
return self._simple_command('SETACL', mailbox, who, what)
'(typ, [data]) = <instance>.setannotation(mailbox[, entry, attribute]+) Set ANNOTATIONs.'
def setannotation(self, *args):
(typ, dat) = self._simple_command('SETANNOTATION', *args) return self._untagged_response(typ, dat, 'ANNOTATION')
'Set the quota root\'s resource limits. (typ, [data]) = <instance>.setquota(root, limits)'
def setquota(self, root, limits):
(typ, dat) = self._simple_command('SETQUOTA', root, limits) return self._untagged_response(typ, dat, 'QUOTA')
'IMAP4rev1 extension SORT command. (typ, [data]) = <instance>.sort(sort_criteria, charset, search_criteria, ...)'
def sort(self, sort_criteria, charset, *search_criteria):
name = 'SORT' if ((sort_criteria[0], sort_criteria[(-1)]) != ('(', ')')): sort_criteria = ('(%s)' % sort_criteria) (typ, dat) = self._simple_command(name, sort_criteria, charset, *search_criteria) return self._untagged_response(typ, dat, name)
'Request named status conditions for mailbox. (typ, [data]) = <instance>.status(mailbox, names)'
def status(self, mailbox, names):
name = 'STATUS' (typ, dat) = self._simple_command(name, mailbox, names) return self._untagged_response(typ, dat, name)
'Alters flag dispositions for messages in mailbox. (typ, [data]) = <instance>.store(message_set, command, flags)'
def store(self, message_set, command, flags):
if ((flags[0], flags[(-1)]) != ('(', ')')): flags = ('(%s)' % flags) (typ, dat) = self._simple_command('STORE', message_set, command, flags) return self._untagged_response(typ, dat, 'FETCH')
'Subscribe to new mailbox. (typ, [data]) = <instance>.subscribe(mailbox)'
def subscribe(self, mailbox):
return self._simple_command('SUBSCRIBE', mailbox)
'IMAPrev1 extension THREAD command. (type, [data]) = <instance>.thread(threading_algorithm, charset, search_criteria, ...)'
def thread(self, threading_algorithm, charset, *search_criteria):
name = 'THREAD' (typ, dat) = self._simple_command(name, threading_algorithm, charset, *search_criteria) return self._untagged_response(typ, dat, name)
'Execute "command arg ..." with messages identified by UID, rather than message number. (typ, [data]) = <instance>.uid(command, arg1, arg2, ...) Returns response appropriate to \'command\'.'
def uid(self, command, *args):
command = command.upper() if (not (command in Commands)): raise self.error(('Unknown IMAP4 UID command: %s' % command)) if (self.state not in Commands[command]): raise self.error(('command %s illegal in state %s, only allowed in states %s' % (command...
'Unsubscribe from old mailbox. (typ, [data]) = <instance>.unsubscribe(mailbox)'
def unsubscribe(self, mailbox):
return self._simple_command('UNSUBSCRIBE', mailbox)
'Allow simple extension commands notified by server in CAPABILITY response. Assumes command is legal in current state. (typ, [data]) = <instance>.xatom(name, arg, ...) Returns response appropriate to extension command `name\'.'
def xatom(self, name, *args):
name = name.upper() if (not (name in Commands)): Commands[name] = (self.state,) return self._simple_command(name, *args)
'Setup a stream connection. This connection will be used by the routines: read, readline, send, shutdown.'
def open(self, host=None, port=None):
self.host = None self.port = None self.sock = None self.file = None self.process = subprocess.Popen(self.command, bufsize=DEFAULT_BUFFER_SIZE, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True, close_fds=True) self.writefile = self.process.stdin self.readfile = self.process.stdout
'Read \'size\' bytes from remote.'
def read(self, size):
return self.readfile.read(size)
'Read line from remote.'
def readline(self):
return self.readfile.readline()
'Send data to remote.'
def send(self, data):
self.writefile.write(data) self.writefile.flush()
'Close I/O established in "open".'
def shutdown(self):
self.readfile.close() self.writefile.close() self.process.wait()
'Close the temporary file, possibly deleting it.'
def close(self):
self._closer.close()
'Instantiate a line-oriented interpreter framework. The optional argument \'completekey\' is the readline name of a completion key; it defaults to the Tab key. If completekey is not None and the readline module is available, command completion is done automatically. The optional arguments stdin and stdout specify alter...
def __init__(self, completekey='tab', stdin=None, stdout=None):
if (stdin is not None): self.stdin = stdin else: self.stdin = sys.stdin if (stdout is not None): self.stdout = stdout else: self.stdout = sys.stdout self.cmdqueue = [] self.completekey = completekey
'Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument.'
def cmdloop(self, intro=None):
self.preloop() if (self.use_rawinput and self.completekey): try: import readline self.old_completer = readline.get_completer() readline.set_completer(self.complete) readline.parse_and_bind((self.completekey + ': complete')) except ImportError: ...
'Hook method executed just before the command line is interpreted, but after the input prompt is generated and issued.'
def precmd(self, line):
return line
'Hook method executed just after a command dispatch is finished.'
def postcmd(self, stop, line):
return stop
'Hook method executed once when the cmdloop() method is called.'
def preloop(self):
pass
'Hook method executed once when the cmdloop() method is about to return.'
def postloop(self):
pass
'Parse the line into a command name and a string containing the arguments. Returns a tuple containing (command, args, line). \'command\' and \'args\' may be None if the line couldn\'t be parsed.'
def parseline(self, line):
line = line.strip() if (not line): return (None, None, line) elif (line[0] == '?'): line = ('help ' + line[1:]) elif (line[0] == '!'): if hasattr(self, 'do_shell'): line = ('shell ' + line[1:]) else: return (None, None, line) (i, n) = (0,...
'Interpret the argument as though it had been typed in response to the prompt. This may be overridden, but should not normally need to be; see the precmd() and postcmd() methods for useful execution hooks. The return value is a flag indicating whether interpretation of commands by the interpreter should stop.'
def onecmd(self, line):
(cmd, arg, line) = self.parseline(line) if (not line): return self.emptyline() if (cmd is None): return self.default(line) self.lastcmd = line if (line == 'EOF'): self.lastcmd = '' if (cmd == ''): return self.default(line) else: try: func =...
'Called when an empty line is entered in response to the prompt. If this method is not overridden, it repeats the last nonempty command entered.'
def emptyline(self):
if self.lastcmd: return self.onecmd(self.lastcmd)
'Called on an input line when the command prefix is not recognized. If this method is not overridden, it prints an error message and returns.'
def default(self, line):
self.stdout.write(('*** Unknown syntax: %s\n' % line))
'Method called to complete an input line when no command-specific complete_*() method is available. By default, it returns an empty list.'
def completedefault(self, *ignored):
return []
'Return the next possible completion for \'text\'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions.'
def complete(self, text, state):
if (state == 0): import readline origline = readline.get_line_buffer() line = origline.lstrip() stripped = (len(origline) - len(line)) begidx = (readline.get_begidx() - stripped) endidx = (readline.get_endidx() - stripped) if (begidx > 0): (cmd, ar...
'List available commands with "help" or detailed help with "help cmd".'
def do_help(self, arg):
if arg: try: func = getattr(self, ('help_' + arg)) except AttributeError: try: doc = getattr(self, ('do_' + arg)).__doc__ if doc: self.stdout.write(('%s\n' % str(doc))) return except Attribute...
'Display a list of strings as a compact set of columns. Each column is only as wide as necessary. Columns are separated by two spaces (one was not legible enough).'
def columnize(self, list, displaywidth=80):
if (not list): self.stdout.write('<empty>\n') return nonstrings = [i for i in range(len(list)) if (not isinstance(list[i], str))] if nonstrings: raise TypeError(('list[i] not a string for i in %s' % ', '.join(map(str, nonstrings)))) size = len(list) if...
'safe: bytes object.'
def __init__(self, safe):
self.safe = _ALWAYS_SAFE.union(safe)
'Returns the time the robots.txt file was last fetched. This is useful for long-running web spiders that need to check for new robots.txt files periodically.'
def mtime(self):
return self.last_checked
'Sets the time the robots.txt file was last fetched to the current time.'
def modified(self):
import time self.last_checked = time.time()
'Sets the URL referring to a robots.txt file.'
def set_url(self, url):
self.url = url (self.host, self.path) = urllib.parse.urlparse(url)[1:3]
'Reads the robots.txt URL and feeds it to the parser.'
def read(self):
try: f = urllib.request.urlopen(self.url) except urllib.error.HTTPError as err: if (err.code in (401, 403)): self.disallow_all = True elif ((err.code >= 400) and (err.code < 500)): self.allow_all = True else: raw = f.read() self.parse(raw.decod...
'Parse the input lines from a robots.txt file. We allow that a user-agent: line is not preceded by one or more blank lines.'
def parse(self, lines):
state = 0 entry = Entry() self.modified() for line in lines: if (not line): if (state == 1): entry = Entry() state = 0 elif (state == 2): self._add_entry(entry) entry = Entry() state = 0 ...
'using the parsed robots.txt decide if useragent can fetch url'
def can_fetch(self, useragent, url):
if self.disallow_all: return False if self.allow_all: return True if (not self.last_checked): return False parsed_url = urllib.parse.urlparse(urllib.parse.unquote(url)) url = urllib.parse.urlunparse(('', '', parsed_url.path, parsed_url.params, parsed_url.query, parsed_url.fra...
'check if this entry applies to the specified agent'
def applies_to(self, useragent):
useragent = useragent.split('/')[0].lower() for agent in self.useragents: if (agent == '*'): return True agent = agent.lower() if (agent in useragent): return True return False