desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Close the cursor.
:raise Warning: Non-fatal warning
:raise Error: Error; unable to close'
| def close(self):
| dbi = self.__driver.get_import()
try:
return self.__cursor.close()
except dbi.Warning as val:
raise Warning(val)
except dbi.Error as val:
raise Error(val)
|
'Execute a SQL statement string with the given parameters.
\'parameters\' is a sequence when the parameter style is
\'format\', \'numeric\' or \'qmark\', and a dictionary when the
style is \'pyformat\' or \'named\'. See ``DB.paramstyle()``.
:Parameters:
statement : str
the SQL statement to execute
parameters : list
par... | def execute(self, statement, parameters=None):
| dbi = self.__driver.get_import()
try:
if parameters:
result = self.__cursor.execute(statement, parameters)
else:
result = self.__cursor.execute(statement)
try:
self.__rowcount = self.__cursor.rowcount
except AttributeError:
self.__r... |
'Execute a SQL statement once for each item in the given parameters.
:Parameters:
statement : str
the SQL statement to execute
parameters : sequence
a sequence of sequences when the parameter style
is \'format\', \'numeric\' or \'qmark\', and a sequence
of dictionaries when the style is \'pyformat\' or
\'named\'.
:rais... | def executemany(self, statement, *parameters):
| dbi = self.__driver.get_import()
try:
result = self.__cursor.executemany(statement, *parameters)
self.__rowcount = self.__cursor.rowcount
self.__description = self.__cursor.description
return result
except dbi.Warning as val:
raise Warning(val)
except dbi.Error as... |
'Returns the next result set row from the last query, as a sequence
of tuples. Raises an exception if the last statement was not a query.
:rtype: tuple
:return: Next result set row
:raise Warning: Non-fatal warning
:raise Error: Error'
| def fetchone(self):
| dbi = self.__driver.get_import()
try:
return self.__cursor.fetchone()
except dbi.Warning as val:
raise Warning(val)
except dbi.Error as val:
raise Error(val)
|
'Returns all remaining result rows from the last query, as a sequence
of tuples. Raises an exception if the last statement was not a query.
:rtype: list of tuples
:return: List of rows, each represented as a tuple
:raise Warning: Non-fatal warning
:raise Error: Error'
| def fetchall(self):
| dbi = self.__driver.get_import()
try:
return self.__cursor.fetchall()
except dbi.Warning as val:
raise Warning(val)
except dbi.Error as val:
raise Error(val)
|
'Returns up to n remaining result rows from the last query, as a
sequence of tuples. Raises an exception if the last statement was
not a query.
:Parameters:
n : int
maximum number of result rows to get
:rtype: list of tuples
:return: List of rows, each represented as a tuple
:raise Warning: Non-fatal warning
:raise Er... | def fetchmany(self, n):
| dbi = self.__driver.get_import()
try:
self.__cursor.fetchmany(n)
except dbi.Warning as val:
raise Warning(val)
except dbi.Error as val:
raise Error(val)
|
'Return data about the RDBMS: the product name, the version,
etc. The result is a named tuple, with the following fields:
vendor
The product vendor, if applicable, or ``None`` if not known
product
The name of the database product, or ``None`` if not known
version
The database product version, or ``None`` if not known
T... | def get_rdbms_metadata(self):
| dbi = self.__driver.get_import()
try:
return self.__driver.get_rdbms_metadata(self.__cursor)
except dbi.Warning as val:
raise Warning(val)
except dbi.Error as val:
raise Error(val)
|
'Get the metadata for a table. Returns a list of tuples, one for
each column. Each tuple consists of the following::
(column_name, type_string, max_char_size, precision, scale, nullable)
The tuple elements have the following meanings.
column_name
the name of the column
type_string
the column type, as a string
max_char_... | def get_table_metadata(self, table):
| dbi = self.__driver.get_import()
try:
return self.__driver.get_table_metadata(table, self.__cursor)
except dbi.Warning as val:
raise Warning(val)
except dbi.Error as val:
raise Error(val)
|
'Get the metadata for the indexes for a table. Returns a list of
tuples, one for each index. Each tuple consists of the following::
(index_name, [index_columns], description)
The tuple elements have the following meanings.
index_name
the index name
index_columns
a list of column names
description
index description, or ... | def get_index_metadata(self, table):
| dbi = self.__driver.get_import()
try:
return self.__driver.get_index_metadata(table, self.__cursor)
except dbi.Warning as val:
raise Warning(val)
except dbi.Error as val:
raise Error(val)
|
'Get the list of tables in the database to which this cursor is
connected.
:rtype: list
:return: List of table names. The list will be empty if the database
contains no tables.
:raise NotImplementedError: Capability not supported by database driver
:raise Warning: Non-fatal warning
:raise Error: ... | def get_tables(self):
| dbi = self.__driver.get_import()
try:
return self.__driver.get_tables(self.__cursor)
except dbi.Warning as val:
raise Warning(val)
except dbi.Error as val:
raise Error(val)
|
'Create a new DB object.
:Parameters:
db
the underlying Python DB API database object
driver : DBDriver
the driver (i.e., the subclass of ``DBDriver``) that
created the ``db`` object'
| def __init__(self, db, driver):
| self.__db = db
self.__driver = driver
dbi = driver.get_import()
for attr in ['BINARY', 'NUMBER', 'STRING', 'DATETIME', 'ROWID']:
try:
exec ('self.%s = dbi.%s' % (attr, attr))
except AttributeError:
exec ('self.%s = 0' % attr)
|
'Get the parameter style for the underlying DB API module. The
result of this method call corresponds exactly to the underlying
DB API module\'s \'paramstyle\' attribute. It will have one of the
following values:
| format | The parameter marker is \'%s\', as in string |
| | formatting. A query... | def paramstyle(self):
| return self.__driver.get_import().paramstyle
|
'Returns an object representing the given string of bytes as a BLOB.
This method is equivalent to the module-level ``Binary()`` method in
an underlying DB API-compliant module.
:Parameters:
string : str
the string to convert to a BLOB
:rtype: object
:return: the corresponding BLOB'
| def Binary(self, string):
| return self.__driver.get_import().Binary(string)
|
'Returns an object representing the specified date.
This method is equivalent to the module-level ``Date()`` method in
an underlying DB API-compliant module.
:Parameters:
year
the year
month
the month
day
the day of the month
:return: an object containing the date'
| def Date(self, year, month, day):
| return self.__driver.get_import().Date(year, month, day)
|
'Returns an object representing the date *secs* seconds after the
epoch. For example:
.. python::
import time
d = db.DateFromTicks(time.time())
This method is equivalent to the module-level ``DateFromTicks()``
method in an underlying DB API-compliant module.
:Parameters:
secs : int
the seconds from the epoch
:return: a... | def DateFromTicks(self, secs):
| date = date.fromtimestamp(secs)
return self.__driver.get_import().Date(date.year, date.month, date.day)
|
'Returns an object representing the specified time.
This method is equivalent to the module-level ``Time()`` method in an
underlying DB API-compliant module.
:Parameters:
hour
the hour of the day
minute
the minute within the hour. 0 <= *minute* <= 59
second
the second within the minute. 0 <= *second* <= 59
:return: an ... | def Time(self, hour, minute, second):
| dt = datetime.fromtimestamp(secs)
return self.__driver.get_import().Time(dt.hour, dt.minute, dt.second)
|
'Returns an object representing the time \'secs\' seconds after the
epoch. For example:
.. python::
import time
d = db.TimeFromTicks(time.time())
This method is equivalent to the module-level ``TimeFromTicks()``
method in an underlying DB API-compliant module.
:Parameters:
secs : int
the seconds from the epoch
:return:... | def TimeFromTicks(self, secs):
| dt = datetime.fromtimestamp(secs)
return self.__driver.get_import().Time(dt.hour, dt.minute, dt.second)
|
'Returns an object representing the specified time.
This method is equivalent to the module-level ``Timestamp()`` method
in an underlying DB API-compliant module.
:Parameters:
year
the year
month
the month
day
the day of the month
hour
the hour of the day
minute
the minute within the hour. 0 <= *minute* <= 59
second
th... | def Timestamp(self, year, month, day, hour, minute, second):
| return self.__driver.get_import().Timestamp(year, month, day, hour, minute, second)
|
'Returns an object representing the date and time ``secs`` seconds
after the epoch. For example:
.. python::
import time
d = db.TimestampFromTicks(time.time())
This method is equivalent to the module-level ``TimestampFromTicks()``
method in an underlying DB API-compliant module.
:Parameters:
secs : int
the seconds from... | def TimestampFromTicks(self, secs):
| dt = datetime.now()
return self.__driver.get_import().Timestamp(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
|
'Get a cursor suitable for accessing the database. The returned object
conforms to the Python DB API cursor interface.
:return: the cursor
:raise Warning: Non-fatal warning
:raise Error: Error'
| def cursor(self):
| dbi = self.__driver.get_import()
try:
return Cursor(self.__db.cursor(), self.__driver)
except dbi.Warning as val:
raise Warning(val)
except dbi.Error as val:
raise Error(val)
|
'Commit the current transaction.
:raise Warning: Non-fatal warning
:raise Error: Error'
| def commit(self):
| dbi = self.__driver.get_import()
try:
self.__db.commit()
except dbi.Warning as val:
raise Warning(val)
except dbi.Error as val:
raise Error(val)
|
'Roll the current transaction back.
:raise Warning: Non-fatal warning
:raise Error: Error'
| def rollback(self):
| dbi = self.__driver.get_import()
try:
self.__db.rollback()
except dbi.Warning as val:
raise Warning(val)
except dbi.Error as val:
raise Error(val)
|
'Close the database connection.
:raise Warning: Non-fatal warning
:raise Error: Error'
| def close(self):
| dbi = self.__driver.get_import()
try:
self.__db.close()
except dbi.Warning as val:
raise Warning(val)
except dbi.Error as val:
raise Error(val)
|
'Get a bound import for the underlying DB API module. All subclasses
must provide an implementation of this method. Here\'s an example,
assuming the real underlying Python DB API module is \'foosql\':
.. python::
def get_import(self):
import foosql
return foosql
:return: a bound module'
| @abstract
def get_import(self):
| pass
|
'Get the driver\'s name, for display. The returned name ought to be
a reasonable identifier for the database (e.g., \'SQL Server\',
\'MySQL\'). All subclasses must provide an implementation of this
method.
:rtype: str
:return: the driver\'s displayable name'
| @abstract
def get_display_name(self):
| pass
|
'Connect to the underlying database. Subclasses should *not*
override this method. Instead, a subclass should override the
``do_connect()`` method.
:Parameters:
host : str
the host where the database lives
port : int
the TCP port to use when connecting, or ``None``
user : str
the user to use when connecting, or ``None`... | def connect(self, host='localhost', port=None, user=None, password='', database=None):
| dbi = self.get_import()
try:
self.__db = self.do_connect(host=host, port=port, user=user, password=password, database=database)
return DB(self.__db, self)
except dbi.Warning as val:
raise Warning(val)
except dbi.Error as val:
raise Error(val)
|
'Connect to the actual underlying database, using the driver.
Subclasses must provide an implementation of this method. The
method must return the result of the real DB API implementation\'s
``connect()`` method. For instance:
.. python::
def do_connect():
dbi = self.get_import()
return dbi.connect(host=host, user=user... | @abstract
def do_connect(self, host='localhost', port=None, user='', password='', database='default'):
| pass
|
'Return data about the RDBMS: the product name, the version,
etc. The result is a named tuple, with the following fields.
vendor
The product vendor, if applicable, or ``None`` if not known
product
The name of the database product, or ``None`` if not known
version
The database product version, or ``None`` if not known
:... | def get_rdbms_metadata(self, cursor):
| return RDBMSMetadata('unknown', 'unknown', 'unknown')
|
'Get the metadata for the indexes for a table. Returns a list of
tuples, one for each index. Each tuple consists of the following::
(index_name, [index_columns], description)
The tuple elements have the following meanings.
index_name
the index name
index_columns
a list of column names
description
index description, or ... | def get_index_metadata(self, table, cursor):
| return None
|
'Get the metadata for a table. Returns a list of tuples, one for
each column. Each tuple consists of the following::
(column_name, type_string, max_char_size, precision, scale, nullable)
The tuple elements have the following meanings.
column_name
the name of the column
type_string
the column type, as a string
max_char_... | def get_table_metadata(self, table, cursor):
| self._ensure_valid_table(cursor, table)
dbi = self.get_import()
cursor.execute(('SELECT * FROM %s WHERE 1=0' % table))
result = []
for col in cursor.description:
name = col[0]
type = col[1]
size = col[2]
internalSize = col[3]
precision = col[4]
... |
'Get the list of tables in the database.
:Parameters:
cursor : Cursor
a ``Cursor`` object from a recent query
:rtype: list
:return: List of table names. The list will be empty if the database
contains no tables.
:raise NotImplementedError: Capability not supported by database driver
:raise Warning: Non-fat... | def get_tables(self, cursor):
| raise NotImplementedError
|
'Determines whether a table name represents a legal table in the
current database, throwing an ``Error`` if not.
:Parameters:
cursor : Cursor
an open ``Cursor``
table_name : str
the table name
:raise Error: bad table name'
| def _ensure_valid_table(self, cursor, table_name):
| if (not self._is_valid_table(cursor, table_name)):
raise Error, ('No such table: "%s"' % table_name)
|
'Determines whether a table name represents a legal table in the
current database, throwing an ``Error`` if not.
:Parameters:
cursor : Cursor
an open ``Cursor``
table_name : str
the table name
:rtype: bool
:return: ``True`` if the table is valid, ``False`` if not'
| def _is_valid_table(self, cursor, table_name):
| tables = self.get_tables(cursor)
return (table_name in tables)
|
'Construct a new ``Configuration`` object.
:Parameters:
defaults : dict
dictionary of default values
permit_includes : bool
whether or not to permit includes
use_ordered_sections : bool
whether or not to use an ordered dictionary for the section
names. If ``True``, then a call to ``sections()`` will return
the sections... | def __init__(self, defaults=None, permit_includes=True, use_ordered_sections=False, strict_substitution=False):
| ConfigParser.SafeConfigParser.__init__(self, defaults)
self.__permit_includes = permit_includes
self.__use_ordered_sections = use_ordered_sections
self.__strict_substitution = strict_substitution
if use_ordered_sections:
self._sections = OrderedDict()
|
'Returns the instance-wide defaults.
:rtype: dict
:return: the instance-wide defaults, or ``None`` if there aren\'t any'
| def defaults(self):
| return ConfigParser.SafeConfigParser.defaults(self)
|
'Get the list of available sections, not including ``DEFAULT``. It\'s
not really useful to call this method before calling ``read()`` or
``readfp()``.
Returns a list of sections.'
| @property
def sections(self):
| return ConfigParser.SafeConfigParser.sections(self)
|
'Add a section named *section* to the instance. If a section by the
given name already exists, ``DuplicateSectionError`` is raised.
:Parameters:
section : str
name of section to add
:raise DuplicateSectionError: section already exists'
| def add_section(self, section):
| ConfigParser.SafeConfigParser.add_section(self, section)
|
'Determine whether a section exists in the configuration. Ignores
the ``DEFAULT`` section.
:Parameters:
section : str
name of section
:rtype: bool
:return: ``True`` if the section exists in the configuration, ``False``
if not.'
| def has_section(self, section):
| return ConfigParser.SafeConfigParser.has_section(self, section)
|
'Get a list of options available in the specified section.
:Parameters:
section : str
name of section
:rtype: list
:return: list of available options. May be empty.
:raise NoSectionError: no such section'
| def options(self, section):
| return ConfigParser.SafeConfigParser.options(self, section)
|
'Determine whether a section has a specific option.
:Parameters:
section : str
name of section
option : str
name of option to check
:rtype: bool
:return: ``True`` if the section exists in the configuration and
has the specified option, ``False`` if not.'
| def has_option(self, section, option):
| return ConfigParser.SafeConfigParser.has_option(self, section, option)
|
'Attempt to read and parse a list of filenames or URLs, returning a
list of filenames or URLs which were successfully parsed. If
*filenames* is a string or Unicode string, it is treated as a single
filename or URL. If a file or URL named in filenames cannot be opened,
that file will be ignored. This is designed so that... | def read(self, filenames):
| if isinstance(filenames, basestring):
filenames = [filenames]
newFilenames = []
for filename in filenames:
try:
self.__preprocess(filename, filename)
newFilenames += [filename]
except IOError:
log.exception(('Error reading "%s"' % filename))
... |
'Read and parse configuration data from a file or file-like object.
(Only the ``readline()`` moethod is used.)
:Parameters:
fp : file
File-like object with a ``readline()`` method
filename : str
Name associated with ``fp``, for error messages. If omitted or
``None``, then ``fp.name`` is used. If ``fp`` has no ``name``
... | def readfp(self, fp, filename=None):
| self.__preprocess(fp, filename)
|
'Get an option from a section.
:Parameters:
section : str
name of section
option : str
name of option to check
optional : bool
``True`` to return None if the option doesn\'t exist. ``False``
to throw an exception if the option doesn\'t exist.
:rtype: str
:return: the option value
:raise NoSectionError: no such section... | def get(self, section, option, optional=False):
| def do_get(section, option):
val = ConfigParser.SafeConfigParser.get(self, section, option)
if (len(val.strip()) == 0):
raise ConfigParser.NoOptionError(option, section)
return val
if optional:
return self.__get_optional(do_get, section, option)
else:
retu... |
'Convenience method that coerces the result of a call to
``get()`` to an ``int``.
:Parameters:
section : str
name of section
option : str
name of option to check
optional : bool
``True`` to return None if the option doesn\'t exist. ``False``
to throw an exception if the option doesn\'t exist.
:rtype: int
:return: the ... | def getint(self, section, option, optional=False):
| def do_get(section, option):
return ConfigParser.SafeConfigParser.getint(self, section, option)
if optional:
return self.__get_optional(do_xget, section, option)
else:
return do_get(section, option)
|
'Convenience method that coerces the result of a call to ``get()`` to a
``float``.
:Parameters:
section : str
name of section
option : str
name of option to check
optional : bool
``True`` to return None if the option doesn\'t exist. ``False``
to throw an exception if the option doesn\'t exist.
:rtype: float
:return: t... | def getfloat(self, section, option, optional=False):
| def do_get(section, option):
return ConfigParser.SafeConfigParser.getfloat(self, section, option)
if optional:
return self.__get_optional(do_get, section, option)
else:
return do_get(section, option)
|
'Convenience method that coerces the result of a call to ``get()`` to a
boolean. Accepted boolean values are "1", "yes", "true", and "on",
which cause this method to return True, and "0", "no", "false", and
"off", which cause it to return False. These string values are checked
in a case-insensitive manner. Any other va... | def getboolean(self, section, option, optional=False):
| def do_get(section, option):
return ConfigParser.SafeConfigParser.getboolean(self, section, option)
if optional:
return self.__get_optional(do_get, section, option)
else:
return do_get(section, option)
|
'Convenience method that coerces the result of a call to ``get()`` to a
list. The value is split using the separator(s) specified by the
``sep`` argument. A ``sep`` value of ``None`` uses white space. The
result is a list of string values.
:Parameters:
section : str
name of section
option : str
name of option to check
... | def getlist(self, section, option, sep=None, optional=False):
| def do_get(section, option):
value = ConfigParser.SafeConfigParser.get(self, section, option)
return value.split(sep)
if optional:
return self.__get_optional(do_get, section, option)
else:
return do_get(section, option)
|
'Retrieve at most one of a list or set of options from a section. This
method is useful if there are multiple possible names for a single
option. For example, suppose you permit either a ``user_name`` or a
``login_name`` option, but not both, in a section called
``credentials``. You can use the following code to retrie... | def get_one_of(self, section, options, optional=False, default=None, value_type=str):
| value = None
if (value_type is bool):
get = self.getboolean
else:
get = self.get
for option in options:
value = get(section, option, optional=True)
if value:
break
if (value is None):
value = default
if ((value is None) and (not optional)):
... |
'Get all items in a section.
:Parameters:
section : str
name of section
:rtype: list
:return: a list of (*name*, *value*) tuples for each option in
in *section*
:raise NoSectionError: no such section'
| def items(self, section):
| return ConfigParser.SafeConfigParser.items(self, section)
|
'If the given section exists, set the given option to the specified
value; otherwise raise ``NoSectionError``.
:Parameters:
section : str
name of section
option : str
name of option to check
value : str
the value to set
:raise NoSectionError: no such section'
| def set(self, section, option, value):
| ConfigParser.SafeConfigParser.set(self, section, option, value)
|
'Write a representation of the configuration to the specified file-like
object. This output can be parsed by a future ``read()`` call.
NOTE: Includes and variable references are ``not`` reconstructed.
That is, the configuration data is written in *expanded* form.
:Parameters:
fileobj : file
file-like object to which to... | def write(self, fileobj):
| ConfigParser.SafeConfigParser.write(self, fileobj)
|
'Remove a section from the instance. If a section by the given name
does not exist, ``NoSectionError`` is raised.
:Parameters:
section : str
name of section to remove
:raise NoSectionError: no such section'
| def remove_section(self, section):
| ConfigParser.SafeConfigParser.remove_section(self, section)
|
'Transforms the option name in ``option_name`` as found in an input
file or as passed in by client code to the form that should be used in
the internal structures. The default implementation returns a
lower-case version of ``option_name``; subclasses may override this or
client code can set an attribute of this name on... | def optionxform(self, option_name):
| return option_name.lower()
|
'Convert all section-local variable references (i.e., those that don\'t
specify a section) to fully-qualified references. Necessary for
recursive references to work.'
| def __normalizeVariableReferences(self, sourceConfig):
| simpleVarRefRe = re.compile(SIMPLE_VARIABLE_REF_PATTERN)
for section in sourceConfig.sections():
for option in sourceConfig.options(section):
value = sourceConfig.get(section, option, raw=True)
oldValue = value
match = simpleVarRefRe.search(value)
while ma... |
'Create a new ``AutoFlush`` object to wrap a file-like object.
:Parameters:
f : file
A file-like object that contains both a ``write()`` method
and a ``flush()`` method.'
| def __init__(self, f):
| self.__file = f
|
'Write the specified buffer to the file.
:Parameters:
buf : str or bytes
buffer to write'
| def write(self, buf):
| self.__file.write(buf)
self.__file.flush()
|
'Force a flush.'
| def flush(self):
| self.__file.flush()
|
'Truncate the underlying file. Might fail.
:Parameters:
size : int
Where to truncate. If less than 0, then file\'s current position
is used.'
| def truncate(self, size=(-1)):
| if (size < 0):
size = self.__file.tell()
self.__file.truncate(size)
|
'Return the file\'s current position, if applicable.
:rtype: int
:return: Current file position'
| def tell(self):
| return self.__file.tell()
|
'Set the file\'s current position. The ``whence`` argument is optional;
legal values are:
- ``os.SEEK_SET`` or 0: absolute file positioning (default)
- ``os.SEEK_CUR`` or 1: seek relative to the current position
- ``os.SEEK_END`` or 2: seek relative to the file\'s end
There is no return value. Note that if the file is ... | def seek(self, offset, whence=os.SEEK_SET):
| self.__file.seek(offset, whence)
|
'Return the integer file descriptor used by the underlying file.
:rtype: int
:return: the file descriptor'
| def fileno(self):
| return self.__file.fileno()
|
'Create a new ``MultiWriter`` object to wrap one or more file-like
objects.
:Parameters:
args : iterable
One or more file-like objects to wrap'
| def __init__(self, *args):
| self.__files = args
|
'Write the specified buffer to the wrapped files.
:Parameters:
buf : str or bytes
buffer to write'
| def write(self, buf):
| for f in self.__files:
f.write(buf)
|
'Force a flush.'
| def flush(self):
| for f in self.__files:
f.flush()
|
'Close all contained files.'
| def close(self):
| for f in self.__files:
f.close()
|
'Create a new ``PushbackFile`` object to wrap a file-like object.
:Parameters:
f : file
A file-like object that contains both a ``write()`` method
and a ``flush()`` method.'
| def __init__(self, f):
| self.__buf = [c for c in ''.join(f.readlines())]
|
'Write the specified buffer to the file. This method throws an
unconditional exception, since ``PushbackFile`` objects are read-only.
:Parameters:
buf : str or bytes
buffer to write
:raise NotImplementedError: unconditionally'
| def write(self, buf):
| raise NotImplementedError, 'PushbackFile is read-only'
|
'Push a character or string back onto the input stream.
:Parameters:
s : str
the string to push back onto the input stream'
| def pushback(self, s):
| self.__buf = ([c for c in s] + self.__buf)
|
'Read *n* bytes from the open file.
:Parameters:
n : int
Number of bytes to read. A negative number instructs
``read()`` to read all remaining bytes.
:return: the bytes read'
| def read(self, n=(-1)):
| resultBuf = None
if (n > len(self.__buf)):
n = len(self.__buf)
if ((n < 0) or (n >= len(self.__buf))):
resultBuf = self.__buf
self.__buf = []
else:
resultBuf = self.__buf[0:n]
self.__buf = self.__buf[n:]
return ''.join(resultBuf)
|
'Read the next line from the file.
:Parameters:
length : int
a length hint, or negative if you don\'t care
:rtype: str
:return: the line'
| def readline(self, length=(-1)):
| i = 0
while ((i < len(self.__buf)) and (self.__buf[i] != '\n')):
i += 1
result = self.__buf[0:(i + 1)]
self.__buf = self.__buf[(i + 1):]
return ''.join(result)
|
'Read all remaining lines in the file.
:rtype: list
:return: list of lines'
| def readlines(self, sizehint=0):
| return self.read((-1))
|
'A file object is its own iterator.
:rtype: str
:return: the next line from the file
:raise StopIteration: end of file
:raise IncludeError: on error'
| def next(self):
| line = self.readline()
if ((line == None) or (len(line) == 0)):
raise StopIteration
return line
|
'Close the file. A no-op in this class.'
| def close(self):
| pass
|
'Force a flush. This method throws an unconditional exception, since
``PushbackFile`` objects are read-only.
:raise NotImplementedError: unconditionally'
| def flush(self):
| raise NotImplementedError, 'PushbackFile is read-only'
|
'Truncate the underlying file. This method throws an unconditional exception, since
``PushbackFile`` objects are read-only.
:Parameters:
size : int
Where to truncate. If less than 0, then file\'s current
position is used
:raise NotImplementedError: unconditionally'
| def truncate(self, size=(-1)):
| raise NotImplementedError, 'PushbackFile is read-only'
|
'Return the file\'s current position, if applicable. This method throws
an unconditional exception, since ``PushbackFile`` objects are
read-only.
:rtype: int
:return: Current file position
:raise NotImplementedError: unconditionally'
| def tell(self):
| raise NotImplementedError, 'PushbackFile is not seekable'
|
'Set the file\'s current position. This method throws an unconditional
exception, since ``PushbackFile`` objects are not seekable.
:Parameters:
offset : int
where to seek
whence : int
see above
:raise NotImplementedError: unconditionally'
| def seek(self, offset, whence=os.SEEK_SET):
| raise NotImplementedError, 'PushbackFile is not seekable'
|
'Return the integer file descriptor used by the underlying file.
:rtype: int
:return: the file descriptor'
| def fileno(self):
| return (-1)
|
'Constructor. Initialize a new zip file.
:Parameters:
file : str
path to zip file
mode : str
open mode. Valid values are \'r\' (read), \'w\' (write), and
\'a\' (append)
compression : int
Compression type. Valid values: ``zipfile.ZIP_STORED`,
``zipfile.ZIP_DEFLATED``
allow_zip64 : bool
Whether or not Zip64 extensions ar... | def __init__(self, file, mode='r', compression=zipfile.ZIP_STORED, allow_zip64=False):
| zipfile.ZipFile.__init__(self, file, mode, compression, allow_zip64)
self.zipFile = file
|
'Unpack the zip file into the specified output directory.
:Parameters:
output_dir : str
path to output directory. The directory is
created if it doesn\'t already exist.'
| def extract(self, output_dir):
| if ((not output_dir.endswith(':')) and (not os.path.exists(output_dir))):
os.mkdir(output_dir)
num_files = len(self.namelist())
for (i, name) in enumerate(self.namelist()):
if (not name.endswith('/')):
directory = os.path.dirname(name)
if (directory == ''):
... |
'Allocate a new file lock that operates on the specified file
descriptor.
:Parameters:
fd : int
Open file descriptor. The file must be opened for writing or
updating, not reading.'
| def __init__(self, fd):
| try:
cls = eval(LOCK_CLASSES[os.name])
self.lock = cls(fd)
except KeyError:
raise NotImplementedError, ('Don\'t know how to lock files on "%s" systems.' % os.name)
|
'Lock the associated file. If someone already has the file locked,
this method will suspend the calling process, unless ``no_wait`` is
``True``.
:Parameters:
no_wait : bool
If ``False``, then ``acquire()`` will suspend the calling
process if someone has the file locked. If ``True``, then
``acquire()`` will raise an ``I... | def acquire(self, no_wait=False):
| self.lock.acquire(no_wait)
|
'Unlock (i.e., release the lock on) the associated file.'
| def release(self):
| self.lock.release()
|
'Parse a line from an FTP ``LIST`` command.
:Parameters:
ftp_list_line : str
The line of output
:rtype: `FTPListData`
:return: An `FTPListData` object describing the parsed line, or
``None`` if the line could not be parsed. Note that it\'s
possible for this method to return a partially-filled
`FTPListData` object (e.g.... | def parse_line(self, ftp_list_line):
| buf = ftp_list_line
if (len(buf) < 2):
return None
c = buf[0]
if (c == '+'):
return self._parse_EPLF(buf)
elif (c in 'bcdlps-'):
return self._parse_unix_style(buf)
i = buf.find(';')
if (i > 0):
return self._parse_multinet(buf, i)
if (c in '0123456789'):
... |
'Create a new instance.'
| def __init__(self, *args, **kw):
| OptionParser.__init__(self, *args, **kw)
self.remove_option('-h')
self.add_option('-h', '--help', action='help', help='Show this message and exit.')
self.epilogue = None
|
'Print the help message, followed by the epilogue (if set), to the
specified output file. You can define an epilogue by setting the
``epilogue`` field.
:Parameters:
out : file
where to write the usage message'
| def print_help(self, out=sys.stderr):
| OptionParser.print_help(self, out)
if self.epilogue:
import textwrap
print >>out, ('\n%s' % textwrap.fill(self.epilogue, 80))
out.flush()
|
'Display a usage message and exit.
:Parameters:
msg : str
If not set to ``None`` (the default), this message will be
displayed before the usage message
exit_code : int
The process exit code. Defaults to 2.'
| def die_with_usage(self, msg=None, exit_code=2):
| if (msg != None):
print >>sys.stderr, msg
self.print_help(sys.stderr)
sys.exit(exit_code)
|
'Overrides parent ``OptionParser`` class\'s ``error()`` method and
forces the full usage message on error.'
| def error(self, msg):
| sys.stderr.write(('%s: error: %s\n' % (self.get_prog_name(), msg)))
self.die_with_usage(msg)
|
'Create a new ``ReadOnly`` object that wraps the ``wrapped`` object
and enforces read-only access to it.
:Parameters:
wrapped : object
the object to wrap'
| def __init__(self, wrapped):
| self.wrapped = wrapped
|
'Dump the history to a file-like object (defaulting to standard output).
:Parameters:
out : file
Where to dump the history.'
| def show(self, out=sys.stdout):
| for i in range(1, (self.total + 1)):
print >>out, ('%4d: %s' % (i, self.get_item(i)))
|
'Get the most recently entered item that matches ``command_name``
at the beginning.
:Parameters:
command_name : str
The string to match against the commands in the history
:rtype: str
:return: the matching string, or ``None``'
| def get_last_matching_item(self, command_name):
| result = None
for i in range(self.get_total(), 0, (-1)):
s = self.get_item(i)
tokens = s.split(None, 1)
if (len(command_name) <= len(s)):
if (s[0:len(command_name)] == command_name):
result = s
break
return result
|
'Get the most recent item in the history.
:rtype: str
:return: The most recent command, or ``None``'
| def get_last_item(self):
| return self.get_item((self.get_total() - 1))
|
'Get an item from the history.
:Parameters:
index : int
0-based index of the item to get. The larger the index
value, the more recent the entry
:rtype: str
:return: the item at that index
:raise IndexError: Index out of range'
| def get_item(self, index):
| return None
|
'Set the completer delimiters--the characters that delimit tokens
that are eligible for completion.
:Parameters:
s : str
The delimiters'
| def set_completer_delims(self, s):
| pass
|
'Get the completer delimiters--the characters that delimit tokens
that are eligible for completion.
:rtype: str
:return: the delimiters'
| def get_completer_delims(self):
| return ''
|
'The total number number of commands in the history. Identical to
calling ``get_total()``.'
| @property
def total(self):
| return self.get_total()
|
'Get the total number number of commands in the history. Identical to
the ``total`` property.
:rtype: int
:return: the number of commands in the history'
| def get_total(self):
| return 0
|
'Get the maximum length of the history. This isn\'t the maximum number
of entries in the in-memory history buffer; instead, it\'s the maximum
number of entries that will be saved to the history file. Subclasses
*must* provide an implementation of this method.
:rtype: int
:return: the maximum saved size of the history'
| @abstract
def get_max_length(self):
| pass
|
'Set the maximum length of the history. This isn\'t the maximum number
of entries in the in-memory history buffer; instead, it\'s the maximum
number of entries that will be saved to the history file. Subclasses
*must* provide an implementation of this method.
:Parameters:
n : int
the maximum saved size of the history'... | @abstract
def set_max_length(self, n):
| pass
|
'Add (append) a line to the history buffer. Subclasses *must* provide
an implementation of this method.
:Parameters:
line : str
the command to append to the history'
| @abstract
def add_item(self, line):
| pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.