code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
182
| url
stringlengths 46
251
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def accumulateClassDict(classObj, attr, adict, baseClass=None):
"""
Accumulate all attributes of a given name in a class hierarchy into a single dictionary.
Assuming all class attributes of this name are dictionaries.
If any of the dictionaries being accumulated have the same key, the
one highest in the class hierarchy wins.
(XXX: If \"highest\" means \"closest to the starting class\".)
Ex::
class Soy:
properties = {\"taste\": \"bland\"}
class Plant:
properties = {\"colour\": \"green\"}
class Seaweed(Plant):
pass
class Lunch(Soy, Seaweed):
properties = {\"vegan\": 1 }
dct = {}
accumulateClassDict(Lunch, \"properties\", dct)
print(dct)
{\"taste\": \"bland\", \"colour\": \"green\", \"vegan\": 1}
"""
for base in classObj.__bases__:
accumulateClassDict(base, attr, adict)
if baseClass is None or baseClass in classObj.__bases__:
adict.update(classObj.__dict__.get(attr, {})) | Accumulate all attributes of a given name in a class hierarchy into a single dictionary.
Assuming all class attributes of this name are dictionaries.
If any of the dictionaries being accumulated have the same key, the
one highest in the class hierarchy wins.
(XXX: If \"highest\" means \"closest to the starting class\".)
Ex::
class Soy:
properties = {\"taste\": \"bland\"}
class Plant:
properties = {\"colour\": \"green\"}
class Seaweed(Plant):
pass
class Lunch(Soy, Seaweed):
properties = {\"vegan\": 1 }
dct = {}
accumulateClassDict(Lunch, \"properties\", dct)
print(dct)
{\"taste\": \"bland\", \"colour\": \"green\", \"vegan\": 1} | accumulateClassDict | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | MIT |
def accumulateClassList(classObj, attr, listObj, baseClass=None):
"""
Accumulate all attributes of a given name in a class hierarchy into a single list.
Assuming all class attributes of this name are lists.
"""
for base in classObj.__bases__:
accumulateClassList(base, attr, listObj)
if baseClass is None or baseClass in classObj.__bases__:
listObj.extend(classObj.__dict__.get(attr, [])) | Accumulate all attributes of a given name in a class hierarchy into a single list.
Assuming all class attributes of this name are lists. | accumulateClassList | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | MIT |
def objgrep(start, goal, eq=isLike, path='', paths=None, seen=None,
showUnknowns=0, maxDepth=None):
"""
An insanely CPU-intensive process for finding stuff.
"""
if paths is None:
paths = []
if seen is None:
seen = {}
if eq(start, goal):
paths.append(path)
if id(start) in seen:
if seen[id(start)] is start:
return
if maxDepth is not None:
if maxDepth == 0:
return
maxDepth -= 1
seen[id(start)] = start
# Make an alias for those arguments which are passed recursively to
# objgrep for container objects.
args = (paths, seen, showUnknowns, maxDepth)
if isinstance(start, dict):
for k, v in start.items():
objgrep(k, goal, eq, path+'{'+repr(v)+'}', *args)
objgrep(v, goal, eq, path+'['+repr(k)+']', *args)
elif isinstance(start, (list, tuple, deque)):
for idx, _elem in enumerate(start):
objgrep(start[idx], goal, eq, path+'['+str(idx)+']', *args)
elif isinstance(start, types.MethodType):
objgrep(start.__self__, goal, eq, path+'.__self__', *args)
objgrep(start.__func__, goal, eq, path+'.__func__', *args)
objgrep(start.__self__.__class__, goal, eq,
path+'.__self__.__class__', *args)
elif hasattr(start, '__dict__'):
for k, v in start.__dict__.items():
objgrep(v, goal, eq, path+'.'+k, *args)
if isinstance(start, compat.InstanceType):
objgrep(start.__class__, goal, eq, path+'.__class__', *args)
elif isinstance(start, weakref.ReferenceType):
objgrep(start(), goal, eq, path+'()', *args)
elif (isinstance(start, (compat.StringType,
int, types.FunctionType,
types.BuiltinMethodType, RegexType, float,
type(None), compat.FileType)) or
type(start).__name__ in ('wrapper_descriptor',
'method_descriptor', 'member_descriptor',
'getset_descriptor')):
pass
elif showUnknowns:
print('unknown type', type(start), start)
return paths | An insanely CPU-intensive process for finding stuff. | objgrep | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | MIT |
def _osUrandom(self, nbytes):
"""
Wrapper around C{os.urandom} that cleanly manage its absence.
"""
try:
return os.urandom(nbytes)
except (AttributeError, NotImplementedError) as e:
raise SourceNotAvailable(e) | Wrapper around C{os.urandom} that cleanly manage its absence. | _osUrandom | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/randbytes.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/randbytes.py | MIT |
def secureRandom(self, nbytes, fallback=False):
"""
Return a number of secure random bytes.
@param nbytes: number of bytes to generate.
@type nbytes: C{int}
@param fallback: Whether the function should fallback on non-secure
random or not. Default to C{False}.
@type fallback: C{bool}
@return: a string of random bytes.
@rtype: C{str}
"""
try:
return self._osUrandom(nbytes)
except SourceNotAvailable:
pass
if fallback:
warnings.warn(
"urandom unavailable - "
"proceeding with non-cryptographically secure random source",
category=RuntimeWarning,
stacklevel=2)
return self.insecureRandom(nbytes)
else:
raise SecureRandomNotAvailable("No secure random source available") | Return a number of secure random bytes.
@param nbytes: number of bytes to generate.
@type nbytes: C{int}
@param fallback: Whether the function should fallback on non-secure
random or not. Default to C{False}.
@type fallback: C{bool}
@return: a string of random bytes.
@rtype: C{str} | secureRandom | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/randbytes.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/randbytes.py | MIT |
def _randBits(self, nbytes):
"""
Wrapper around C{os.getrandbits}.
"""
if self.getrandbits is not None:
n = self.getrandbits(nbytes * 8)
hexBytes = ("%%0%dx" % (nbytes * 2)) % n
return _fromhex(hexBytes)
raise SourceNotAvailable("random.getrandbits is not available") | Wrapper around C{os.getrandbits}. | _randBits | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/randbytes.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/randbytes.py | MIT |
def _randModule(self, nbytes):
"""
Wrapper around the C{random} module.
"""
return b"".join([
bytes([random.choice(self._BYTES)]) for i in range(nbytes)]) | Wrapper around the C{random} module. | _randModule | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/randbytes.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/randbytes.py | MIT |
def insecureRandom(self, nbytes):
"""
Return a number of non secure random bytes.
@param nbytes: number of bytes to generate.
@type nbytes: C{int}
@return: a string of random bytes.
@rtype: C{str}
"""
for src in ("_randBits", "_randModule"):
try:
return getattr(self, src)(nbytes)
except SourceNotAvailable:
pass | Return a number of non secure random bytes.
@param nbytes: number of bytes to generate.
@type nbytes: C{int}
@return: a string of random bytes.
@rtype: C{str} | insecureRandom | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/randbytes.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/randbytes.py | MIT |
def _fullyQualifiedName(obj):
"""
Return the fully qualified name of a module, class, method or function.
Classes and functions need to be module level ones to be correctly
qualified.
@rtype: C{str}.
"""
try:
name = obj.__qualname__
except AttributeError:
name = obj.__name__
if inspect.isclass(obj) or inspect.isfunction(obj):
moduleName = obj.__module__
return "%s.%s" % (moduleName, name)
elif inspect.ismethod(obj):
try:
cls = obj.im_class
except AttributeError:
# Python 3 eliminates im_class, substitutes __module__ and
# __qualname__ to provide similar information.
return "%s.%s" % (obj.__module__, obj.__qualname__)
else:
className = _fullyQualifiedName(cls)
return "%s.%s" % (className, name)
return name | Return the fully qualified name of a module, class, method or function.
Classes and functions need to be module level ones to be correctly
qualified.
@rtype: C{str}. | _fullyQualifiedName | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def _getReplacementString(replacement):
"""
Surround a replacement for a deprecated API with some polite text exhorting
the user to consider it as an alternative.
@type replacement: C{str} or callable
@return: a string like "please use twisted.python.modules.getModule
instead".
"""
if callable(replacement):
replacement = _fullyQualifiedName(replacement)
return "please use %s instead" % (replacement,) | Surround a replacement for a deprecated API with some polite text exhorting
the user to consider it as an alternative.
@type replacement: C{str} or callable
@return: a string like "please use twisted.python.modules.getModule
instead". | _getReplacementString | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def _getDeprecationDocstring(version, replacement=None):
"""
Generate an addition to a deprecated object's docstring that explains its
deprecation.
@param version: the version it was deprecated.
@type version: L{incremental.Version}
@param replacement: The replacement, if specified.
@type replacement: C{str} or callable
@return: a string like "Deprecated in Twisted 27.2.0; please use
twisted.timestream.tachyon.flux instead."
"""
doc = "Deprecated in %s" % (getVersionString(version),)
if replacement:
doc = "%s; %s" % (doc, _getReplacementString(replacement))
return doc + "." | Generate an addition to a deprecated object's docstring that explains its
deprecation.
@param version: the version it was deprecated.
@type version: L{incremental.Version}
@param replacement: The replacement, if specified.
@type replacement: C{str} or callable
@return: a string like "Deprecated in Twisted 27.2.0; please use
twisted.timestream.tachyon.flux instead." | _getDeprecationDocstring | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def _getDeprecationWarningString(fqpn, version, format=None, replacement=None):
"""
Return a string indicating that the Python name was deprecated in the given
version.
@param fqpn: Fully qualified Python name of the thing being deprecated
@type fqpn: C{str}
@param version: Version that C{fqpn} was deprecated in.
@type version: L{incremental.Version}
@param format: A user-provided format to interpolate warning values into, or
L{DEPRECATION_WARNING_FORMAT
<twisted.python.deprecate.DEPRECATION_WARNING_FORMAT>} if L{None} is
given.
@type format: C{str}
@param replacement: what should be used in place of C{fqpn}. Either pass in
a string, which will be inserted into the warning message, or a
callable, which will be expanded to its full import path.
@type replacement: C{str} or callable
@return: A textual description of the deprecation
@rtype: C{str}
"""
if format is None:
format = DEPRECATION_WARNING_FORMAT
warningString = format % {
'fqpn': fqpn,
'version': getVersionString(version)}
if replacement:
warningString = "%s; %s" % (
warningString, _getReplacementString(replacement))
return warningString | Return a string indicating that the Python name was deprecated in the given
version.
@param fqpn: Fully qualified Python name of the thing being deprecated
@type fqpn: C{str}
@param version: Version that C{fqpn} was deprecated in.
@type version: L{incremental.Version}
@param format: A user-provided format to interpolate warning values into, or
L{DEPRECATION_WARNING_FORMAT
<twisted.python.deprecate.DEPRECATION_WARNING_FORMAT>} if L{None} is
given.
@type format: C{str}
@param replacement: what should be used in place of C{fqpn}. Either pass in
a string, which will be inserted into the warning message, or a
callable, which will be expanded to its full import path.
@type replacement: C{str} or callable
@return: A textual description of the deprecation
@rtype: C{str} | _getDeprecationWarningString | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def getDeprecationWarningString(callableThing, version, format=None,
replacement=None):
"""
Return a string indicating that the callable was deprecated in the given
version.
@type callableThing: C{callable}
@param callableThing: Callable object to be deprecated
@type version: L{incremental.Version}
@param version: Version that C{callableThing} was deprecated in
@type format: C{str}
@param format: A user-provided format to interpolate warning values into,
or L{DEPRECATION_WARNING_FORMAT
<twisted.python.deprecate.DEPRECATION_WARNING_FORMAT>} if L{None} is
given
@param callableThing: A callable to be deprecated.
@param version: The L{incremental.Version} that the callable
was deprecated in.
@param replacement: what should be used in place of the callable. Either
pass in a string, which will be inserted into the warning message,
or a callable, which will be expanded to its full import path.
@type replacement: C{str} or callable
@return: A string describing the deprecation.
@rtype: C{str}
"""
return _getDeprecationWarningString(
_fullyQualifiedName(callableThing), version, format, replacement) | Return a string indicating that the callable was deprecated in the given
version.
@type callableThing: C{callable}
@param callableThing: Callable object to be deprecated
@type version: L{incremental.Version}
@param version: Version that C{callableThing} was deprecated in
@type format: C{str}
@param format: A user-provided format to interpolate warning values into,
or L{DEPRECATION_WARNING_FORMAT
<twisted.python.deprecate.DEPRECATION_WARNING_FORMAT>} if L{None} is
given
@param callableThing: A callable to be deprecated.
@param version: The L{incremental.Version} that the callable
was deprecated in.
@param replacement: what should be used in place of the callable. Either
pass in a string, which will be inserted into the warning message,
or a callable, which will be expanded to its full import path.
@type replacement: C{str} or callable
@return: A string describing the deprecation.
@rtype: C{str} | getDeprecationWarningString | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def _appendToDocstring(thingWithDoc, textToAppend):
"""
Append the given text to the docstring of C{thingWithDoc}.
If C{thingWithDoc} has no docstring, then the text just replaces the
docstring. If it has a single-line docstring then it appends a blank line
and the message text. If it has a multi-line docstring, then in appends a
blank line a the message text, and also does the indentation correctly.
"""
if thingWithDoc.__doc__:
docstringLines = thingWithDoc.__doc__.splitlines()
else:
docstringLines = []
if len(docstringLines) == 0:
docstringLines.append(textToAppend)
elif len(docstringLines) == 1:
docstringLines.extend(['', textToAppend, ''])
else:
spaces = docstringLines.pop()
docstringLines.extend(['',
spaces + textToAppend,
spaces])
thingWithDoc.__doc__ = '\n'.join(docstringLines) | Append the given text to the docstring of C{thingWithDoc}.
If C{thingWithDoc} has no docstring, then the text just replaces the
docstring. If it has a single-line docstring then it appends a blank line
and the message text. If it has a multi-line docstring, then in appends a
blank line a the message text, and also does the indentation correctly. | _appendToDocstring | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def deprecationDecorator(function):
"""
Decorator that marks C{function} as deprecated.
"""
warningString = getDeprecationWarningString(
function, version, None, replacement)
@wraps(function)
def deprecatedFunction(*args, **kwargs):
warn(
warningString,
DeprecationWarning,
stacklevel=2)
return function(*args, **kwargs)
_appendToDocstring(deprecatedFunction,
_getDeprecationDocstring(version, replacement))
deprecatedFunction.deprecatedVersion = version
return deprecatedFunction | Decorator that marks C{function} as deprecated. | deprecated.deprecationDecorator | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def deprecated(version, replacement=None):
"""
Return a decorator that marks callables as deprecated. To deprecate a
property, see L{deprecatedProperty}.
@type version: L{incremental.Version}
@param version: The version in which the callable will be marked as
having been deprecated. The decorated function will be annotated
with this version, having it set as its C{deprecatedVersion}
attribute.
@param version: the version that the callable was deprecated in.
@type version: L{incremental.Version}
@param replacement: what should be used in place of the callable. Either
pass in a string, which will be inserted into the warning message,
or a callable, which will be expanded to its full import path.
@type replacement: C{str} or callable
"""
def deprecationDecorator(function):
"""
Decorator that marks C{function} as deprecated.
"""
warningString = getDeprecationWarningString(
function, version, None, replacement)
@wraps(function)
def deprecatedFunction(*args, **kwargs):
warn(
warningString,
DeprecationWarning,
stacklevel=2)
return function(*args, **kwargs)
_appendToDocstring(deprecatedFunction,
_getDeprecationDocstring(version, replacement))
deprecatedFunction.deprecatedVersion = version
return deprecatedFunction
return deprecationDecorator | Return a decorator that marks callables as deprecated. To deprecate a
property, see L{deprecatedProperty}.
@type version: L{incremental.Version}
@param version: The version in which the callable will be marked as
having been deprecated. The decorated function will be annotated
with this version, having it set as its C{deprecatedVersion}
attribute.
@param version: the version that the callable was deprecated in.
@type version: L{incremental.Version}
@param replacement: what should be used in place of the callable. Either
pass in a string, which will be inserted into the warning message,
or a callable, which will be expanded to its full import path.
@type replacement: C{str} or callable | deprecated | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def deprecatedProperty(version, replacement=None):
"""
Return a decorator that marks a property as deprecated. To deprecate a
regular callable or class, see L{deprecated}.
@type version: L{incremental.Version}
@param version: The version in which the callable will be marked as
having been deprecated. The decorated function will be annotated
with this version, having it set as its C{deprecatedVersion}
attribute.
@param version: the version that the callable was deprecated in.
@type version: L{incremental.Version}
@param replacement: what should be used in place of the callable.
Either pass in a string, which will be inserted into the warning
message, or a callable, which will be expanded to its full import
path.
@type replacement: C{str} or callable
@return: A new property with deprecated setter and getter.
@rtype: C{property}
@since: 16.1.0
"""
class _DeprecatedProperty(property):
"""
Extension of the build-in property to allow deprecated setters.
"""
def _deprecatedWrapper(self, function):
@wraps(function)
def deprecatedFunction(*args, **kwargs):
warn(
self.warningString,
DeprecationWarning,
stacklevel=2)
return function(*args, **kwargs)
return deprecatedFunction
def setter(self, function):
return property.setter(self, self._deprecatedWrapper(function))
def deprecationDecorator(function):
if _PY3:
warningString = getDeprecationWarningString(
function, version, None, replacement)
else:
# Because Python 2 sucks, we need to implement our own here -- lack
# of __qualname__ means that we kinda have to stack walk. It maybe
# probably works. Probably. -Amber
functionName = function.__name__
className = inspect.stack()[1][3] # wow hax
moduleName = function.__module__
fqdn = "%s.%s.%s" % (moduleName, className, functionName)
warningString = _getDeprecationWarningString(
fqdn, version, None, replacement)
@wraps(function)
def deprecatedFunction(*args, **kwargs):
warn(
warningString,
DeprecationWarning,
stacklevel=2)
return function(*args, **kwargs)
_appendToDocstring(deprecatedFunction,
_getDeprecationDocstring(version, replacement))
deprecatedFunction.deprecatedVersion = version
result = _DeprecatedProperty(deprecatedFunction)
result.warningString = warningString
return result
return deprecationDecorator | Return a decorator that marks a property as deprecated. To deprecate a
regular callable or class, see L{deprecated}.
@type version: L{incremental.Version}
@param version: The version in which the callable will be marked as
having been deprecated. The decorated function will be annotated
with this version, having it set as its C{deprecatedVersion}
attribute.
@param version: the version that the callable was deprecated in.
@type version: L{incremental.Version}
@param replacement: what should be used in place of the callable.
Either pass in a string, which will be inserted into the warning
message, or a callable, which will be expanded to its full import
path.
@type replacement: C{str} or callable
@return: A new property with deprecated setter and getter.
@rtype: C{property}
@since: 16.1.0 | deprecatedProperty | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def getWarningMethod():
"""
Return the warning method currently used to record deprecation warnings.
"""
return warn | Return the warning method currently used to record deprecation warnings. | getWarningMethod | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def setWarningMethod(newMethod):
"""
Set the warning method to use to record deprecation warnings.
The callable should take message, category and stacklevel. The return
value is ignored.
"""
global warn
warn = newMethod | Set the warning method to use to record deprecation warnings.
The callable should take message, category and stacklevel. The return
value is ignored. | setWarningMethod | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def __repr__(self):
"""
Get a string containing the type of the module proxy and a
representation of the wrapped module object.
"""
state = _InternalState(self)
return '<%s module=%r>' % (type(self).__name__, state._module) | Get a string containing the type of the module proxy and a
representation of the wrapped module object. | __repr__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def __setattr__(self, name, value):
"""
Set an attribute on the wrapped module object.
"""
state = _InternalState(self)
state._lastWasPath = False
setattr(state._module, name, value) | Set an attribute on the wrapped module object. | __setattr__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def __getattribute__(self, name):
"""
Get an attribute from the module object, possibly emitting a warning.
If the specified name has been deprecated, then a warning is issued.
(Unless certain obscure conditions are met; see
L{_ModuleProxy._lastWasPath} for more information about what might quash
such a warning.)
"""
state = _InternalState(self)
if state._lastWasPath:
deprecatedAttribute = None
else:
deprecatedAttribute = state._deprecatedAttributes.get(name)
if deprecatedAttribute is not None:
# If we have a _DeprecatedAttribute object from the earlier lookup,
# allow it to issue the warning.
value = deprecatedAttribute.get()
else:
# Otherwise, just retrieve the underlying value directly; it's not
# deprecated, there's no warning to issue.
value = getattr(state._module, name)
if name == '__path__':
state._lastWasPath = True
else:
state._lastWasPath = False
return value | Get an attribute from the module object, possibly emitting a warning.
If the specified name has been deprecated, then a warning is issued.
(Unless certain obscure conditions are met; see
L{_ModuleProxy._lastWasPath} for more information about what might quash
such a warning.) | __getattribute__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def __init__(self, module, name, version, message):
"""
Initialise a deprecated name wrapper.
"""
self.module = module
self.__name__ = name
self.fqpn = module.__name__ + '.' + name
self.version = version
self.message = message | Initialise a deprecated name wrapper. | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def get(self):
"""
Get the underlying attribute value and issue a deprecation warning.
"""
# This might fail if the deprecated thing is a module inside a package.
# In that case, don't emit the warning this time. The import system
# will come back again when it's not an AttributeError and we can emit
# the warning then.
result = getattr(self.module, self.__name__)
message = _getDeprecationWarningString(self.fqpn, self.version,
DEPRECATION_WARNING_FORMAT + ': ' + self.message)
warn(message, DeprecationWarning, stacklevel=3)
return result | Get the underlying attribute value and issue a deprecation warning. | get | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def _deprecateAttribute(proxy, name, version, message):
"""
Mark a module-level attribute as being deprecated.
@type proxy: L{_ModuleProxy}
@param proxy: The module proxy instance proxying the deprecated attributes
@type name: C{str}
@param name: Attribute name
@type version: L{incremental.Version}
@param version: Version that the attribute was deprecated in
@type message: C{str}
@param message: Deprecation message
"""
_module = object.__getattribute__(proxy, '_module')
attr = _DeprecatedAttribute(_module, name, version, message)
# Add a deprecated attribute marker for this module's attribute. When this
# attribute is accessed via _ModuleProxy a warning is emitted.
_deprecatedAttributes = object.__getattribute__(
proxy, '_deprecatedAttributes')
_deprecatedAttributes[name] = attr | Mark a module-level attribute as being deprecated.
@type proxy: L{_ModuleProxy}
@param proxy: The module proxy instance proxying the deprecated attributes
@type name: C{str}
@param name: Attribute name
@type version: L{incremental.Version}
@param version: Version that the attribute was deprecated in
@type message: C{str}
@param message: Deprecation message | _deprecateAttribute | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def deprecatedModuleAttribute(version, message, moduleName, name):
"""
Declare a module-level attribute as being deprecated.
@type version: L{incremental.Version}
@param version: Version that the attribute was deprecated in
@type message: C{str}
@param message: Deprecation message
@type moduleName: C{str}
@param moduleName: Fully-qualified Python name of the module containing
the deprecated attribute; if called from the same module as the
attributes are being deprecated in, using the C{__name__} global can
be helpful
@type name: C{str}
@param name: Attribute name to deprecate
"""
module = sys.modules[moduleName]
if not isinstance(module, _ModuleProxy):
module = _ModuleProxy(module)
sys.modules[moduleName] = module
_deprecateAttribute(module, name, version, message) | Declare a module-level attribute as being deprecated.
@type version: L{incremental.Version}
@param version: Version that the attribute was deprecated in
@type message: C{str}
@param message: Deprecation message
@type moduleName: C{str}
@param moduleName: Fully-qualified Python name of the module containing
the deprecated attribute; if called from the same module as the
attributes are being deprecated in, using the C{__name__} global can
be helpful
@type name: C{str}
@param name: Attribute name to deprecate | deprecatedModuleAttribute | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def warnAboutFunction(offender, warningString):
"""
Issue a warning string, identifying C{offender} as the responsible code.
This function is used to deprecate some behavior of a function. It differs
from L{warnings.warn} in that it is not limited to deprecating the behavior
of a function currently on the call stack.
@param function: The function that is being deprecated.
@param warningString: The string that should be emitted by this warning.
@type warningString: C{str}
@since: 11.0
"""
# inspect.getmodule() is attractive, but somewhat
# broken in Python < 2.6. See Python bug 4845.
offenderModule = sys.modules[offender.__module__]
filename = inspect.getabsfile(offenderModule)
lineStarts = list(findlinestarts(offender.__code__))
lastLineNo = lineStarts[-1][1]
globals = offender.__globals__
kwargs = dict(
category=DeprecationWarning,
filename=filename,
lineno=lastLineNo,
module=offenderModule.__name__,
registry=globals.setdefault("__warningregistry__", {}),
module_globals=None)
warn_explicit(warningString, **kwargs) | Issue a warning string, identifying C{offender} as the responsible code.
This function is used to deprecate some behavior of a function. It differs
from L{warnings.warn} in that it is not limited to deprecating the behavior
of a function currently on the call stack.
@param function: The function that is being deprecated.
@param warningString: The string that should be emitted by this warning.
@type warningString: C{str}
@since: 11.0 | warnAboutFunction | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def _passedArgSpec(argspec, positional, keyword):
"""
Take an I{inspect.ArgSpec}, a tuple of positional arguments, and a dict of
keyword arguments, and return a mapping of arguments that were actually
passed to their passed values.
@param argspec: The argument specification for the function to inspect.
@type argspec: I{inspect.ArgSpec}
@param positional: The positional arguments that were passed.
@type positional: L{tuple}
@param keyword: The keyword arguments that were passed.
@type keyword: L{dict}
@return: A dictionary mapping argument names (those declared in C{argspec})
to values that were passed explicitly by the user.
@rtype: L{dict} mapping L{str} to L{object}
"""
result = {}
unpassed = len(argspec.args) - len(positional)
if argspec.keywords is not None:
kwargs = result[argspec.keywords] = {}
if unpassed < 0:
if argspec.varargs is None:
raise TypeError("Too many arguments.")
else:
result[argspec.varargs] = positional[len(argspec.args):]
for name, value in zip(argspec.args, positional):
result[name] = value
for name, value in keyword.items():
if name in argspec.args:
if name in result:
raise TypeError("Already passed.")
result[name] = value
elif argspec.keywords is not None:
kwargs[name] = value
else:
raise TypeError("no such param")
return result | Take an I{inspect.ArgSpec}, a tuple of positional arguments, and a dict of
keyword arguments, and return a mapping of arguments that were actually
passed to their passed values.
@param argspec: The argument specification for the function to inspect.
@type argspec: I{inspect.ArgSpec}
@param positional: The positional arguments that were passed.
@type positional: L{tuple}
@param keyword: The keyword arguments that were passed.
@type keyword: L{dict}
@return: A dictionary mapping argument names (those declared in C{argspec})
to values that were passed explicitly by the user.
@rtype: L{dict} mapping L{str} to L{object} | _passedArgSpec | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def _passedSignature(signature, positional, keyword):
"""
Take an L{inspect.Signature}, a tuple of positional arguments, and a dict of
keyword arguments, and return a mapping of arguments that were actually
passed to their passed values.
@param signature: The signature of the function to inspect.
@type signature: L{inspect.Signature}
@param positional: The positional arguments that were passed.
@type positional: L{tuple}
@param keyword: The keyword arguments that were passed.
@type keyword: L{dict}
@return: A dictionary mapping argument names (those declared in
C{signature}) to values that were passed explicitly by the user.
@rtype: L{dict} mapping L{str} to L{object}
"""
result = {}
kwargs = None
numPositional = 0
for (n, (name, param)) in enumerate(signature.parameters.items()):
if param.kind == inspect.Parameter.VAR_POSITIONAL:
# Varargs, for example: *args
result[name] = positional[n:]
numPositional = len(result[name]) + 1
elif param.kind == inspect.Parameter.VAR_KEYWORD:
# Variable keyword args, for example: **my_kwargs
kwargs = result[name] = {}
elif param.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD,
inspect.Parameter.POSITIONAL_ONLY):
if n < len(positional):
result[name] = positional[n]
numPositional += 1
elif param.kind == inspect.Parameter.KEYWORD_ONLY:
if name not in keyword:
if param.default == inspect.Parameter.empty:
raise TypeError("missing keyword arg {}".format(name))
else:
result[name] = param.default
else:
raise TypeError("'{}' parameter is invalid kind: {}".format(
name, param.kind))
if len(positional) > numPositional:
raise TypeError("Too many arguments.")
for name, value in keyword.items():
if name in signature.parameters.keys():
if name in result:
raise TypeError("Already passed.")
result[name] = value
elif kwargs is not None:
kwargs[name] = value
else:
raise TypeError("no such param")
return result | Take an L{inspect.Signature}, a tuple of positional arguments, and a dict of
keyword arguments, and return a mapping of arguments that were actually
passed to their passed values.
@param signature: The signature of the function to inspect.
@type signature: L{inspect.Signature}
@param positional: The positional arguments that were passed.
@type positional: L{tuple}
@param keyword: The keyword arguments that were passed.
@type keyword: L{dict}
@return: A dictionary mapping argument names (those declared in
C{signature}) to values that were passed explicitly by the user.
@rtype: L{dict} mapping L{str} to L{object} | _passedSignature | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def _mutuallyExclusiveArguments(argumentPairs):
"""
Decorator which causes its decoratee to raise a L{TypeError} if two of the
given arguments are passed at the same time.
@param argumentPairs: pairs of argument identifiers, each pair indicating
an argument that may not be passed in conjunction with another.
@type argumentPairs: sequence of 2-sequences of L{str}
@return: A decorator, used like so::
@_mutuallyExclusiveArguments([["tweedledum", "tweedledee"]])
def function(tweedledum=1, tweedledee=2):
"Don't pass tweedledum and tweedledee at the same time."
@rtype: 1-argument callable taking a callable and returning a callable.
"""
def wrapper(wrappee):
if getattr(inspect, "signature", None):
# Python 3
spec = inspect.signature(wrappee)
_passed = _passedSignature
else:
# Python 2
spec = inspect.getargspec(wrappee)
_passed = _passedArgSpec
@wraps(wrappee)
def wrapped(*args, **kwargs):
arguments = _passed(spec, args, kwargs)
for this, that in argumentPairs:
if this in arguments and that in arguments:
raise TypeError(
("The %r and %r arguments to %s "
"are mutually exclusive.") %
(this, that, _fullyQualifiedName(wrappee)))
return wrappee(*args, **kwargs)
return wrapped
return wrapper | Decorator which causes its decoratee to raise a L{TypeError} if two of the
given arguments are passed at the same time.
@param argumentPairs: pairs of argument identifiers, each pair indicating
an argument that may not be passed in conjunction with another.
@type argumentPairs: sequence of 2-sequences of L{str}
@return: A decorator, used like so::
@_mutuallyExclusiveArguments([["tweedledum", "tweedledee"]])
def function(tweedledum=1, tweedledee=2):
"Don't pass tweedledum and tweedledee at the same time."
@rtype: 1-argument callable taking a callable and returning a callable. | _mutuallyExclusiveArguments | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/deprecate.py | MIT |
def which(name, flags=os.X_OK):
"""
Search PATH for executable files with the given name.
On newer versions of MS-Windows, the PATHEXT environment variable will be
set to the list of file extensions for files considered executable. This
will normally include things like ".EXE". This function will also find files
with the given name ending with any of these extensions.
On MS-Windows the only flag that has any meaning is os.F_OK. Any other
flags will be ignored.
@type name: C{str}
@param name: The name for which to search.
@type flags: C{int}
@param flags: Arguments to L{os.access}.
@rtype: C{list}
@param: A list of the full paths to files found, in the order in which they
were found.
"""
result = []
exts = list(filter(None, os.environ.get('PATHEXT', '').split(os.pathsep)))
path = os.environ.get('PATH', None)
if path is None:
return []
for p in os.environ.get('PATH', '').split(os.pathsep):
p = os.path.join(p, name)
if os.access(p, flags):
result.append(p)
for e in exts:
pext = p + e
if os.access(pext, flags):
result.append(pext)
return result | Search PATH for executable files with the given name.
On newer versions of MS-Windows, the PATHEXT environment variable will be
set to the list of file extensions for files considered executable. This
will normally include things like ".EXE". This function will also find files
with the given name ending with any of these extensions.
On MS-Windows the only flag that has any meaning is os.F_OK. Any other
flags will be ignored.
@type name: C{str}
@param name: The name for which to search.
@type flags: C{int}
@param flags: Arguments to L{os.access}.
@rtype: C{list}
@param: A list of the full paths to files found, in the order in which they
were found. | which | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/procutils.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/procutils.py | MIT |
def __init__(self, name, directory, defaultMode=None):
"""
Create a log file.
@param name: name of the file
@param directory: directory holding the file
@param defaultMode: permissions used to create the file. Default to
current permissions of the file if the file exists.
"""
self.directory = directory
self.name = name
self.path = os.path.join(directory, name)
if defaultMode is None and os.path.exists(self.path):
self.defaultMode = stat.S_IMODE(os.stat(self.path)[stat.ST_MODE])
else:
self.defaultMode = defaultMode
self._openFile() | Create a log file.
@param name: name of the file
@param directory: directory holding the file
@param defaultMode: permissions used to create the file. Default to
current permissions of the file if the file exists. | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | MIT |
def fromFullPath(cls, filename, *args, **kwargs):
"""
Construct a log file from a full file path.
"""
logPath = os.path.abspath(filename)
return cls(os.path.basename(logPath),
os.path.dirname(logPath), *args, **kwargs) | Construct a log file from a full file path. | fromFullPath | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | MIT |
def shouldRotate(self):
"""
Override with a method to that returns true if the log
should be rotated.
"""
raise NotImplementedError | Override with a method to that returns true if the log
should be rotated. | shouldRotate | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | MIT |
def _openFile(self):
"""
Open the log file.
The log file is always opened in binary mode.
"""
self.closed = False
if os.path.exists(self.path):
self._file = open(self.path, "rb+", 0)
self._file.seek(0, 2)
else:
if self.defaultMode is not None:
# Set the lowest permissions
oldUmask = os.umask(0o777)
try:
self._file = open(self.path, "wb+", 0)
finally:
os.umask(oldUmask)
else:
self._file = open(self.path, "wb+", 0)
if self.defaultMode is not None:
try:
os.chmod(self.path, self.defaultMode)
except OSError:
# Probably /dev/null or something?
pass | Open the log file.
The log file is always opened in binary mode. | _openFile | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | MIT |
def write(self, data):
"""
Write some data to the file.
@param data: The data to write. Text will be encoded as UTF-8.
@type data: L{bytes} or L{unicode}
"""
if self.shouldRotate():
self.flush()
self.rotate()
if isinstance(data, unicode):
data = data.encode('utf8')
self._file.write(data) | Write some data to the file.
@param data: The data to write. Text will be encoded as UTF-8.
@type data: L{bytes} or L{unicode} | write | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | MIT |
def close(self):
"""
Close the file.
The file cannot be used once it has been closed.
"""
self.closed = True
self._file.close()
self._file = None | Close the file.
The file cannot be used once it has been closed. | close | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | MIT |
def reopen(self):
"""
Reopen the log file. This is mainly useful if you use an external log
rotation tool, which moves under your feet.
Note that on Windows you probably need a specific API to rename the
file, as it's not supported to simply use os.rename, for example.
"""
self.close()
self._openFile() | Reopen the log file. This is mainly useful if you use an external log
rotation tool, which moves under your feet.
Note that on Windows you probably need a specific API to rename the
file, as it's not supported to simply use os.rename, for example. | reopen | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | MIT |
def getCurrentLog(self):
"""
Return a LogReader for the current log file.
"""
return LogReader(self.path) | Return a LogReader for the current log file. | getCurrentLog | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | MIT |
def __init__(self, name, directory, rotateLength=1000000, defaultMode=None,
maxRotatedFiles=None):
"""
Create a log file rotating on length.
@param name: file name.
@type name: C{str}
@param directory: path of the log file.
@type directory: C{str}
@param rotateLength: size of the log file where it rotates. Default to
1M.
@type rotateLength: C{int}
@param defaultMode: mode used to create the file.
@type defaultMode: C{int}
@param maxRotatedFiles: if not None, max number of log files the class
creates. Warning: it removes all log files above this number.
@type maxRotatedFiles: C{int}
"""
BaseLogFile.__init__(self, name, directory, defaultMode)
self.rotateLength = rotateLength
self.maxRotatedFiles = maxRotatedFiles | Create a log file rotating on length.
@param name: file name.
@type name: C{str}
@param directory: path of the log file.
@type directory: C{str}
@param rotateLength: size of the log file where it rotates. Default to
1M.
@type rotateLength: C{int}
@param defaultMode: mode used to create the file.
@type defaultMode: C{int}
@param maxRotatedFiles: if not None, max number of log files the class
creates. Warning: it removes all log files above this number.
@type maxRotatedFiles: C{int} | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | MIT |
def shouldRotate(self):
"""
Rotate when the log file size is larger than rotateLength.
"""
return self.rotateLength and self.size >= self.rotateLength | Rotate when the log file size is larger than rotateLength. | shouldRotate | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | MIT |
def getLog(self, identifier):
"""
Given an integer, return a LogReader for an old log file.
"""
filename = "%s.%d" % (self.path, identifier)
if not os.path.exists(filename):
raise ValueError("no such logfile exists")
return LogReader(filename) | Given an integer, return a LogReader for an old log file. | getLog | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | MIT |
def write(self, data):
"""
Write some data to the file.
"""
BaseLogFile.write(self, data)
self.size += len(data) | Write some data to the file. | write | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | MIT |
def listLogs(self):
"""
Return sorted list of integers - the old logs' identifiers.
"""
result = []
for name in glob.glob("%s.*" % self.path):
try:
counter = int(name.split('.')[-1])
if counter:
result.append(counter)
except ValueError:
pass
result.sort()
return result | Return sorted list of integers - the old logs' identifiers. | listLogs | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | MIT |
def getLog(self, identifier):
"""Given a unix time, return a LogReader for an old log file."""
if self.toDate(identifier) == self.lastDate:
return self.getCurrentLog()
filename = "%s.%s" % (self.path, self.suffix(identifier))
if not os.path.exists(filename):
raise ValueError("no such logfile exists")
return LogReader(filename) | Given a unix time, return a LogReader for an old log file. | getLog | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | MIT |
def write(self, data):
"""Write some data to the log file"""
BaseLogFile.write(self, data)
# Guard against a corner case where time.time()
# could potentially run backwards to yesterday.
# Primarily due to network time.
self.lastDate = max(self.lastDate, self.toDate()) | Write some data to the log file | write | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | MIT |
def __init__(self, name):
"""
Open the log file for reading.
The comments about binary-mode for L{BaseLogFile._openFile} also apply
here.
"""
self._file = open(name, "r") | Open the log file for reading.
The comments about binary-mode for L{BaseLogFile._openFile} also apply
here. | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | MIT |
def readLines(self, lines=10):
"""Read a list of lines from the log file.
This doesn't returns all of the files lines - call it multiple times.
"""
result = []
for i in range(lines):
line = self._file.readline()
if not line:
break
result.append(line)
return result | Read a list of lines from the log file.
This doesn't returns all of the files lines - call it multiple times. | readLines | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/logfile.py | MIT |
def stringyString(object, indentation=''):
"""
Expansive string formatting for sequence types.
C{list.__str__} and C{dict.__str__} use C{repr()} to display their
elements. This function also turns these sequence types
into strings, but uses C{str()} on their elements instead.
Sequence elements are also displayed on separate lines, and nested
sequences have nested indentation.
"""
braces = ''
sl = []
if type(object) is dict:
braces = '{}'
for key, value in object.items():
value = stringyString(value, indentation + ' ')
if isMultiline(value):
if endsInNewline(value):
value = value[:-len('\n')]
sl.append("%s %s:\n%s" % (indentation, key, value))
else:
# Oops. Will have to move that indentation.
sl.append("%s %s: %s" % (indentation, key,
value[len(indentation) + 3:]))
elif type(object) is tuple or type(object) is list:
if type(object) is tuple:
braces = '()'
else:
braces = '[]'
for element in object:
element = stringyString(element, indentation + ' ')
sl.append(element.rstrip() + ',')
else:
sl[:] = map(lambda s, i=indentation: i + s,
str(object).split('\n'))
if not sl:
sl.append(indentation)
if braces:
sl[0] = indentation + braces[0] + sl[0][len(indentation) + 1:]
sl[-1] = sl[-1] + braces[-1]
s = "\n".join(sl)
if isMultiline(s) and not endsInNewline(s):
s = s + '\n'
return s | Expansive string formatting for sequence types.
C{list.__str__} and C{dict.__str__} use C{repr()} to display their
elements. This function also turns these sequence types
into strings, but uses C{str()} on their elements instead.
Sequence elements are also displayed on separate lines, and nested
sequences have nested indentation. | stringyString | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/text.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/text.py | MIT |
def isMultiline(s):
"""
Returns C{True} if this string has a newline in it.
"""
return (s.find('\n') != -1) | Returns C{True} if this string has a newline in it. | isMultiline | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/text.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/text.py | MIT |
def endsInNewline(s):
"""
Returns C{True} if this string ends in a newline.
"""
return (s[-len('\n'):] == '\n') | Returns C{True} if this string ends in a newline. | endsInNewline | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/text.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/text.py | MIT |
def greedyWrap(inString, width=80):
"""
Given a string and a column width, return a list of lines.
Caveat: I'm use a stupid greedy word-wrapping
algorythm. I won't put two spaces at the end
of a sentence. I don't do full justification.
And no, I've never even *heard* of hypenation.
"""
outLines = []
#eww, evil hacks to allow paragraphs delimited by two \ns :(
if inString.find('\n\n') >= 0:
paragraphs = inString.split('\n\n')
for para in paragraphs:
outLines.extend(greedyWrap(para, width) + [''])
return outLines
inWords = inString.split()
column = 0
ptr_line = 0
while inWords:
column = column + len(inWords[ptr_line])
ptr_line = ptr_line + 1
if (column > width):
if ptr_line == 1:
# This single word is too long, it will be the whole line.
pass
else:
# We've gone too far, stop the line one word back.
ptr_line = ptr_line - 1
(l, inWords) = (inWords[0:ptr_line], inWords[ptr_line:])
outLines.append(' '.join(l))
ptr_line = 0
column = 0
elif not (len(inWords) > ptr_line):
# Clean up the last bit.
outLines.append(' '.join(inWords))
del inWords[:]
else:
# Space
column = column + 1
# next word
return outLines | Given a string and a column width, return a list of lines.
Caveat: I'm use a stupid greedy word-wrapping
algorythm. I won't put two spaces at the end
of a sentence. I don't do full justification.
And no, I've never even *heard* of hypenation. | greedyWrap | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/text.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/text.py | MIT |
def splitQuoted(s):
"""
Like a string split, but don't break substrings inside quotes.
>>> splitQuoted('the "hairy monkey" likes pie')
['the', 'hairy monkey', 'likes', 'pie']
Another one of those "someone must have a better solution for
this" things. This implementation is a VERY DUMB hack done too
quickly.
"""
out = []
quot = None
phrase = None
for word in s.split():
if phrase is None:
if word and (word[0] in ("\"", "'")):
quot = word[0]
word = word[1:]
phrase = []
if phrase is None:
out.append(word)
else:
if word and (word[-1] == quot):
word = word[:-1]
phrase.append(word)
out.append(" ".join(phrase))
phrase = None
else:
phrase.append(word)
return out | Like a string split, but don't break substrings inside quotes.
>>> splitQuoted('the "hairy monkey" likes pie')
['the', 'hairy monkey', 'likes', 'pie']
Another one of those "someone must have a better solution for
this" things. This implementation is a VERY DUMB hack done too
quickly. | splitQuoted | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/text.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/text.py | MIT |
def strFile(p, f, caseSensitive=True):
"""
Find whether string C{p} occurs in a read()able object C{f}.
@rtype: C{bool}
"""
buf = type(p)()
buf_len = max(len(p), 2**2**2**2)
if not caseSensitive:
p = p.lower()
while 1:
r = f.read(buf_len-len(p))
if not caseSensitive:
r = r.lower()
bytes_read = len(r)
if bytes_read == 0:
return False
l = len(buf)+bytes_read-buf_len
if l <= 0:
buf = buf + r
else:
buf = buf[l:] + r
if buf.find(p) != -1:
return True | Find whether string C{p} occurs in a read()able object C{f}.
@rtype: C{bool} | strFile | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/text.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/text.py | MIT |
def _shouldEnableNewStyle():
"""
Returns whether or not we should enable the new-style conversion of
old-style classes. It inspects the environment for C{TWISTED_NEWSTYLE},
accepting an empty string, C{no}, C{false}, C{False}, and C{0} as falsey
values and everything else as a truthy value.
@rtype: L{bool}
"""
value = os.environ.get('TWISTED_NEWSTYLE', '')
if value in ['', 'no', 'false', 'False', '0']:
return False
else:
return True | Returns whether or not we should enable the new-style conversion of
old-style classes. It inspects the environment for C{TWISTED_NEWSTYLE},
accepting an empty string, C{no}, C{false}, C{False}, and C{0} as falsey
values and everything else as a truthy value.
@rtype: L{bool} | _shouldEnableNewStyle | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | MIT |
def currentframe(n=0):
"""
In Python 3, L{inspect.currentframe} does not take a stack-level argument.
Restore that functionality from Python 2 so we don't have to re-implement
the C{f_back}-walking loop in places where it's called.
@param n: The number of stack levels above the caller to walk.
@type n: L{int}
@return: a frame, n levels up the stack from the caller.
@rtype: L{types.FrameType}
"""
f = inspect.currentframe()
for x in range(n + 1):
f = f.f_back
return f | In Python 3, L{inspect.currentframe} does not take a stack-level argument.
Restore that functionality from Python 2 so we don't have to re-implement
the C{f_back}-walking loop in places where it's called.
@param n: The number of stack levels above the caller to walk.
@type n: L{int}
@return: a frame, n levels up the stack from the caller.
@rtype: L{types.FrameType} | currentframe | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | MIT |
def inet_pton(af, addr):
"""
Emulator of L{socket.inet_pton}.
@param af: An address family to parse; C{socket.AF_INET} or
C{socket.AF_INET6}.
@type af: L{int}
@param addr: An address.
@type addr: native L{str}
@return: The binary packed version of the passed address.
@rtype: L{bytes}
"""
if not addr:
raise ValueError("illegal IP address string passed to inet_pton")
if af == socket.AF_INET:
return socket.inet_aton(addr)
elif af == getattr(socket, 'AF_INET6', 'AF_INET6'):
if '%' in addr and (addr.count('%') > 1 or addr.index("%") == 0):
raise ValueError("illegal IP address string passed to inet_pton")
addr = addr.split('%')[0]
parts = addr.split(':')
elided = parts.count('')
ipv4Component = '.' in parts[-1]
if len(parts) > (8 - ipv4Component) or elided > 3:
raise ValueError("Syntactically invalid address")
if elided == 3:
return '\x00' * 16
if elided:
zeros = ['0'] * (8 - len(parts) - ipv4Component + elided)
if addr.startswith('::'):
parts[:2] = zeros
elif addr.endswith('::'):
parts[-2:] = zeros
else:
idx = parts.index('')
parts[idx:idx+1] = zeros
if len(parts) != 8 - ipv4Component:
raise ValueError("Syntactically invalid address")
else:
if len(parts) != (8 - ipv4Component):
raise ValueError("Syntactically invalid address")
if ipv4Component:
if parts[-1].count('.') != 3:
raise ValueError("Syntactically invalid address")
rawipv4 = socket.inet_aton(parts[-1])
unpackedipv4 = struct.unpack('!HH', rawipv4)
parts[-1:] = [hex(x)[2:] for x in unpackedipv4]
parts = [int(x, 16) for x in parts]
return struct.pack('!8H', *parts)
else:
raise socket.error(97, 'Address family not supported by protocol') | Emulator of L{socket.inet_pton}.
@param af: An address family to parse; C{socket.AF_INET} or
C{socket.AF_INET6}.
@type af: L{int}
@param addr: An address.
@type addr: native L{str}
@return: The binary packed version of the passed address.
@rtype: L{bytes} | inet_pton | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | MIT |
def execfile(filename, globals, locals=None):
"""
Execute a Python script in the given namespaces.
Similar to the execfile builtin, but a namespace is mandatory, partly
because that's a sensible thing to require, and because otherwise we'd
have to do some frame hacking.
This is a compatibility implementation for Python 3 porting, to avoid the
use of the deprecated builtin C{execfile} function.
"""
if locals is None:
locals = globals
with open(filename, "rb") as fin:
source = fin.read()
code = compile(source, filename, "exec")
exec(code, globals, locals) | Execute a Python script in the given namespaces.
Similar to the execfile builtin, but a namespace is mandatory, partly
because that's a sensible thing to require, and because otherwise we'd
have to do some frame hacking.
This is a compatibility implementation for Python 3 porting, to avoid the
use of the deprecated builtin C{execfile} function. | execfile | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | MIT |
def ioType(fileIshObject, default=unicode):
"""
Determine the type which will be returned from the given file object's
read() and accepted by its write() method as an argument.
In other words, determine whether the given file is 'opened in text mode'.
@param fileIshObject: Any object, but ideally one which resembles a file.
@type fileIshObject: L{object}
@param default: A default value to return when the type of C{fileIshObject}
cannot be determined.
@type default: L{type}
@return: There are 3 possible return values:
1. L{unicode}, if the file is unambiguously opened in text mode.
2. L{bytes}, if the file is unambiguously opened in binary mode.
3. L{basestring}, if we are on python 2 (the L{basestring} type
does not exist on python 3) and the file is opened in binary
mode, but has an encoding and can therefore accept both bytes
and text reliably for writing, but will return L{bytes} from
read methods.
4. The C{default} parameter, if the given type is not understood.
@rtype: L{type}
"""
if isinstance(fileIshObject, TextIOBase):
# If it's for text I/O, then it's for text I/O.
return unicode
if isinstance(fileIshObject, IOBase):
# If it's for I/O but it's _not_ for text I/O, it's for bytes I/O.
return bytes
encoding = getattr(fileIshObject, 'encoding', None)
import codecs
if isinstance(fileIshObject, (codecs.StreamReader, codecs.StreamWriter)):
# On StreamReaderWriter, the 'encoding' attribute has special meaning;
# it is unambiguously unicode.
if encoding:
return unicode
else:
return bytes
if not _PY3:
# Special case: if we have an encoding file, we can *give* it unicode,
# but we can't expect to *get* unicode.
if isinstance(fileIshObject, file):
if encoding is not None:
return basestring
else:
return bytes
from cStringIO import InputType, OutputType
from StringIO import StringIO
if isinstance(fileIshObject, (StringIO, InputType, OutputType)):
return bytes
return default | Determine the type which will be returned from the given file object's
read() and accepted by its write() method as an argument.
In other words, determine whether the given file is 'opened in text mode'.
@param fileIshObject: Any object, but ideally one which resembles a file.
@type fileIshObject: L{object}
@param default: A default value to return when the type of C{fileIshObject}
cannot be determined.
@type default: L{type}
@return: There are 3 possible return values:
1. L{unicode}, if the file is unambiguously opened in text mode.
2. L{bytes}, if the file is unambiguously opened in binary mode.
3. L{basestring}, if we are on python 2 (the L{basestring} type
does not exist on python 3) and the file is opened in binary
mode, but has an encoding and can therefore accept both bytes
and text reliably for writing, but will return L{bytes} from
read methods.
4. The C{default} parameter, if the given type is not understood.
@rtype: L{type} | ioType | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | MIT |
def nativeString(s):
"""
Convert C{bytes} or C{unicode} to the native C{str} type, using ASCII
encoding if conversion is necessary.
@raise UnicodeError: The input string is not ASCII encodable/decodable.
@raise TypeError: The input is neither C{bytes} nor C{unicode}.
"""
if not isinstance(s, (bytes, unicode)):
raise TypeError("%r is neither bytes nor unicode" % s)
if _PY3:
if isinstance(s, bytes):
return s.decode("ascii")
else:
# Ensure we're limited to ASCII subset:
s.encode("ascii")
else:
if isinstance(s, unicode):
return s.encode("ascii")
else:
# Ensure we're limited to ASCII subset:
s.decode("ascii")
return s | Convert C{bytes} or C{unicode} to the native C{str} type, using ASCII
encoding if conversion is necessary.
@raise UnicodeError: The input string is not ASCII encodable/decodable.
@raise TypeError: The input is neither C{bytes} nor C{unicode}. | nativeString | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | MIT |
def _matchingString(constantString, inputString):
"""
Some functions, such as C{os.path.join}, operate on string arguments which
may be bytes or text, and wish to return a value of the same type. In
those cases you may wish to have a string constant (in the case of
C{os.path.join}, that constant would be C{os.path.sep}) involved in the
parsing or processing, that must be of a matching type in order to use
string operations on it. L{_matchingString} will take a constant string
(either L{bytes} or L{unicode}) and convert it to the same type as the
input string. C{constantString} should contain only characters from ASCII;
to ensure this, it will be encoded or decoded regardless.
@param constantString: A string literal used in processing.
@type constantString: L{unicode} or L{bytes}
@param inputString: A byte string or text string provided by the user.
@type inputString: L{unicode} or L{bytes}
@return: C{constantString} converted into the same type as C{inputString}
@rtype: the type of C{inputString}
"""
if isinstance(constantString, bytes):
otherType = constantString.decode("ascii")
else:
otherType = constantString.encode("ascii")
if type(constantString) == type(inputString):
return constantString
else:
return otherType | Some functions, such as C{os.path.join}, operate on string arguments which
may be bytes or text, and wish to return a value of the same type. In
those cases you may wish to have a string constant (in the case of
C{os.path.join}, that constant would be C{os.path.sep}) involved in the
parsing or processing, that must be of a matching type in order to use
string operations on it. L{_matchingString} will take a constant string
(either L{bytes} or L{unicode}) and convert it to the same type as the
input string. C{constantString} should contain only characters from ASCII;
to ensure this, it will be encoded or decoded regardless.
@param constantString: A string literal used in processing.
@type constantString: L{unicode} or L{bytes}
@param inputString: A byte string or text string provided by the user.
@type inputString: L{unicode} or L{bytes}
@return: C{constantString} converted into the same type as C{inputString}
@rtype: the type of C{inputString} | _matchingString | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | MIT |
def lazyByteSlice(object, offset=0, size=None):
"""
Return a copy of the given bytes-like object.
If an offset is given, the copy starts at that offset. If a size is
given, the copy will only be of that length.
@param object: C{bytes} to be copied.
@param offset: C{int}, starting index of copy.
@param size: Optional, if an C{int} is given limit the length of copy
to this size.
"""
view = memoryview(object)
if size is None:
return view[offset:]
else:
return view[offset:(offset + size)] | Return a copy of the given bytes-like object.
If an offset is given, the copy starts at that offset. If a size is
given, the copy will only be of that length.
@param object: C{bytes} to be copied.
@param offset: C{int}, starting index of copy.
@param size: Optional, if an C{int} is given limit the length of copy
to this size. | lazyByteSlice | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | MIT |
def _keys(d):
"""
Return a list of the keys of C{d}.
@type d: L{dict}
@rtype: L{list}
"""
if _PY3:
return list(d.keys())
else:
return d.keys() | Return a list of the keys of C{d}.
@type d: L{dict}
@rtype: L{list} | _keys | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | MIT |
def bytesEnviron():
"""
Return a L{dict} of L{os.environ} where all text-strings are encoded into
L{bytes}.
This function is POSIX only; environment variables are always text strings
on Windows.
"""
if not _PY3:
# On py2, nothing to do.
return dict(os.environ)
target = dict()
for x, y in os.environ.items():
target[os.environ.encodekey(x)] = os.environ.encodevalue(y)
return target | Return a L{dict} of L{os.environ} where all text-strings are encoded into
L{bytes}.
This function is POSIX only; environment variables are always text strings
on Windows. | bytesEnviron | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | MIT |
def _constructMethod(cls, name, self):
"""
Construct a bound method.
@param cls: The class that the method should be bound to.
@type cls: L{types.ClassType} or L{type}.
@param name: The name of the method.
@type name: native L{str}
@param self: The object that the method is bound to.
@type self: any object
@return: a bound method
@rtype: L{types.MethodType}
"""
func = cls.__dict__[name]
if _PY3:
return _MethodType(func, self)
return _MethodType(func, self, cls) | Construct a bound method.
@param cls: The class that the method should be bound to.
@type cls: L{types.ClassType} or L{type}.
@param name: The name of the method.
@type name: native L{str}
@param self: The object that the method is bound to.
@type self: any object
@return: a bound method
@rtype: L{types.MethodType} | _constructMethod | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | MIT |
def _bytesChr(i):
"""
Like L{chr} but always works on ASCII, returning L{bytes}.
@param i: The ASCII code point to return.
@type i: L{int}
@rtype: L{bytes}
"""
if _PY3:
return bytes([i])
else:
return chr(i) | Like L{chr} but always works on ASCII, returning L{bytes}.
@param i: The ASCII code point to return.
@type i: L{int}
@rtype: L{bytes} | _bytesChr | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | MIT |
def _coercedUnicode(s):
"""
Coerce ASCII-only byte strings into unicode for Python 2.
In Python 2 C{unicode(b'bytes')} returns a unicode string C{'bytes'}. In
Python 3, the equivalent C{str(b'bytes')} will return C{"b'bytes'"}
instead. This function mimics the behavior for Python 2. It will decode the
byte string as ASCII. In Python 3 it simply raises a L{TypeError} when
passing a byte string. Unicode strings are returned as-is.
@param s: The string to coerce.
@type s: L{bytes} or L{unicode}
@raise UnicodeError: The input L{bytes} is not ASCII decodable.
@raise TypeError: The input is L{bytes} on Python 3.
"""
if isinstance(s, bytes):
if _PY3:
raise TypeError("Expected str not %r (bytes)" % (s,))
else:
return s.decode('ascii')
else:
return s | Coerce ASCII-only byte strings into unicode for Python 2.
In Python 2 C{unicode(b'bytes')} returns a unicode string C{'bytes'}. In
Python 3, the equivalent C{str(b'bytes')} will return C{"b'bytes'"}
instead. This function mimics the behavior for Python 2. It will decode the
byte string as ASCII. In Python 3 it simply raises a L{TypeError} when
passing a byte string. Unicode strings are returned as-is.
@param s: The string to coerce.
@type s: L{bytes} or L{unicode}
@raise UnicodeError: The input L{bytes} is not ASCII decodable.
@raise TypeError: The input is L{bytes} on Python 3. | _coercedUnicode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | MIT |
def _bytesRepr(bytestring):
"""
Provide a repr for a byte string that begins with 'b' on both
Python 2 and 3.
@param bytestring: The string to repr.
@type bytestring: L{bytes}
@raise TypeError: The input is not L{bytes}.
@return: The repr with a leading 'b'.
@rtype: L{bytes}
"""
if not isinstance(bytestring, bytes):
raise TypeError("Expected bytes not %r" % (bytestring,))
if _PY3:
return repr(bytestring)
else:
return 'b' + repr(bytestring) | Provide a repr for a byte string that begins with 'b' on both
Python 2 and 3.
@param bytestring: The string to repr.
@type bytestring: L{bytes}
@raise TypeError: The input is not L{bytes}.
@return: The repr with a leading 'b'.
@rtype: L{bytes} | _bytesRepr | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | MIT |
def _get_async_param(isAsync=None, **kwargs):
"""
Provide a backwards-compatible way to get async param value that does not
cause a syntax error under Python 3.7.
@param isAsync: isAsync param value (should default to None)
@type isAsync: L{bool}
@param kwargs: keyword arguments of the caller (only async is allowed)
@type kwargs: L{dict}
@raise TypeError: Both isAsync and async specified.
@return: Final isAsync param value
@rtype: L{bool}
"""
if 'async' in kwargs:
warnings.warn(
"'async' keyword argument is deprecated, please use isAsync",
DeprecationWarning, stacklevel=2)
if isAsync is None and 'async' in kwargs:
isAsync = kwargs.pop('async')
if kwargs:
raise TypeError
return bool(isAsync) | Provide a backwards-compatible way to get async param value that does not
cause a syntax error under Python 3.7.
@param isAsync: isAsync param value (should default to None)
@type isAsync: L{bool}
@param kwargs: keyword arguments of the caller (only async is allowed)
@type kwargs: L{dict}
@raise TypeError: Both isAsync and async specified.
@return: Final isAsync param value
@rtype: L{bool} | _get_async_param | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/compat.py | MIT |
def open(filename):
"""
Open an existing shortcut for reading.
@return: The shortcut object
@rtype: Shortcut
"""
sc = Shortcut()
sc.load(filename)
return sc | Open an existing shortcut for reading.
@return: The shortcut object
@rtype: Shortcut | open | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/shortcut.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/shortcut.py | MIT |
def __init__(self,
path=None,
arguments=None,
description=None,
workingdir=None,
iconpath=None,
iconidx=0):
"""
@param path: Location of the target
@param arguments: If path points to an executable, optional arguments
to pass
@param description: Human-readable description of target
@param workingdir: Directory from which target is launched
@param iconpath: Filename that contains an icon for the shortcut
@param iconidx: If iconpath is set, optional index of the icon desired
"""
self._base = pythoncom.CoCreateInstance(
shell.CLSID_ShellLink, None,
pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink
)
if path is not None:
self.SetPath(os.path.abspath(path))
if arguments is not None:
self.SetArguments(arguments)
if description is not None:
self.SetDescription(description)
if workingdir is not None:
self.SetWorkingDirectory(os.path.abspath(workingdir))
if iconpath is not None:
self.SetIconLocation(os.path.abspath(iconpath), iconidx) | @param path: Location of the target
@param arguments: If path points to an executable, optional arguments
to pass
@param description: Human-readable description of target
@param workingdir: Directory from which target is launched
@param iconpath: Filename that contains an icon for the shortcut
@param iconidx: If iconpath is set, optional index of the icon desired | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/shortcut.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/shortcut.py | MIT |
def load(self, filename):
"""
Read a shortcut file from disk.
"""
self._base.QueryInterface(pythoncom.IID_IPersistFile).Load(
os.path.abspath(filename)) | Read a shortcut file from disk. | load | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/shortcut.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/shortcut.py | MIT |
def save(self, filename):
"""
Write the shortcut to disk.
The file should be named something.lnk.
"""
self._base.QueryInterface(pythoncom.IID_IPersistFile).Save(
os.path.abspath(filename), 0) | Write the shortcut to disk.
The file should be named something.lnk. | save | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/shortcut.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/shortcut.py | MIT |
def __init__(self, prefix, options=DEFAULT_OPTIONS,
facility=DEFAULT_FACILITY):
"""
@type prefix: C{str}
@param prefix: The syslog prefix to use.
@type options: C{int}
@param options: A bitvector represented as an integer of the syslog
options to use.
@type facility: C{int}
@param facility: An indication to the syslog daemon of what sort of
program this is (essentially, an additional arbitrary metadata
classification for messages sent to syslog by this observer).
"""
self.openlog(prefix, options, facility) | @type prefix: C{str}
@param prefix: The syslog prefix to use.
@type options: C{int}
@param options: A bitvector represented as an integer of the syslog
options to use.
@type facility: C{int}
@param facility: An indication to the syslog daemon of what sort of
program this is (essentially, an additional arbitrary metadata
classification for messages sent to syslog by this observer). | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/syslog.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/syslog.py | MIT |
def emit(self, eventDict):
"""
Send a message event to the I{syslog}.
@param eventDict: The event to send. If it has no C{'message'} key, it
will be ignored. Otherwise, if it has C{'syslogPriority'} and/or
C{'syslogFacility'} keys, these will be used as the syslog priority
and facility. If it has no C{'syslogPriority'} key but a true
value for the C{'isError'} key, the B{LOG_ALERT} priority will be
used; if it has a false value for C{'isError'}, B{LOG_INFO} will be
used. If the C{'message'} key is multiline, each line will be sent
to the syslog separately.
"""
# Figure out what the message-text is.
text = log.textFromEventDict(eventDict)
if text is None:
return
# Figure out what syslog parameters we might need to use.
priority = syslog.LOG_INFO
facility = 0
if eventDict['isError']:
priority = syslog.LOG_ALERT
if 'syslogPriority' in eventDict:
priority = int(eventDict['syslogPriority'])
if 'syslogFacility' in eventDict:
facility = int(eventDict['syslogFacility'])
# Break the message up into lines and send them.
lines = text.split('\n')
while lines[-1:] == ['']:
lines.pop()
firstLine = True
for line in lines:
if firstLine:
firstLine = False
else:
line = '\t' + line
self.syslog(priority | facility,
'[%s] %s' % (eventDict['system'], line)) | Send a message event to the I{syslog}.
@param eventDict: The event to send. If it has no C{'message'} key, it
will be ignored. Otherwise, if it has C{'syslogPriority'} and/or
C{'syslogFacility'} keys, these will be used as the syslog priority
and facility. If it has no C{'syslogPriority'} key but a true
value for the C{'isError'} key, the B{LOG_ALERT} priority will be
used; if it has a false value for C{'isError'}, B{LOG_INFO} will be
used. If the C{'message'} key is multiline, each line will be sent
to the syslog separately. | emit | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/syslog.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/syslog.py | MIT |
def startLogging(prefix='Twisted', options=DEFAULT_OPTIONS,
facility=DEFAULT_FACILITY, setStdout=1):
"""
Send all Twisted logging output to syslog from now on.
The prefix, options and facility arguments are passed to
C{syslog.openlog()}, see the Python syslog documentation for details. For
other parameters, see L{twisted.python.log.startLoggingWithObserver}.
"""
obs = SyslogObserver(prefix, options, facility)
log.startLoggingWithObserver(obs.emit, setStdout=setStdout) | Send all Twisted logging output to syslog from now on.
The prefix, options and facility arguments are passed to
C{syslog.openlog()}, see the Python syslog documentation for details. For
other parameters, see L{twisted.python.log.startLoggingWithObserver}. | startLogging | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/syslog.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/syslog.py | MIT |
def runCommand(args, **kwargs):
"""Execute a vector of arguments.
This is a wrapper around L{subprocess.check_output}, so it takes
the same arguments as L{subprocess.Popen} with one difference: all
arguments after the vector must be keyword arguments.
@param args: arguments passed to L{subprocess.check_output}
@param kwargs: keyword arguments passed to L{subprocess.check_output}
@return: command output
@rtype: L{bytes}
"""
kwargs['stderr'] = STDOUT
return check_output(args, **kwargs) | Execute a vector of arguments.
This is a wrapper around L{subprocess.check_output}, so it takes
the same arguments as L{subprocess.Popen} with one difference: all
arguments after the vector must be keyword arguments.
@param args: arguments passed to L{subprocess.check_output}
@param kwargs: keyword arguments passed to L{subprocess.check_output}
@return: command output
@rtype: L{bytes} | runCommand | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | MIT |
def ensureIsWorkingDirectory(path):
"""
Ensure that C{path} is a working directory of this VCS.
@type path: L{twisted.python.filepath.FilePath}
@param path: The path to check.
""" | Ensure that C{path} is a working directory of this VCS.
@type path: L{twisted.python.filepath.FilePath}
@param path: The path to check. | ensureIsWorkingDirectory | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | MIT |
def isStatusClean(path):
"""
Return the Git status of the files in the specified path.
@type path: L{twisted.python.filepath.FilePath}
@param path: The path to get the status from (can be a directory or a
file.)
""" | Return the Git status of the files in the specified path.
@type path: L{twisted.python.filepath.FilePath}
@param path: The path to get the status from (can be a directory or a
file.) | isStatusClean | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | MIT |
def remove(path):
"""
Remove the specified path from a the VCS.
@type path: L{twisted.python.filepath.FilePath}
@param path: The path to remove from the repository.
""" | Remove the specified path from a the VCS.
@type path: L{twisted.python.filepath.FilePath}
@param path: The path to remove from the repository. | remove | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | MIT |
def exportTo(fromDir, exportDir):
"""
Export the content of the VCSrepository to the specified directory.
@type fromDir: L{twisted.python.filepath.FilePath}
@param fromDir: The path to the VCS repository to export.
@type exportDir: L{twisted.python.filepath.FilePath}
@param exportDir: The directory to export the content of the
repository to. This directory doesn't have to exist prior to
exporting the repository.
""" | Export the content of the VCSrepository to the specified directory.
@type fromDir: L{twisted.python.filepath.FilePath}
@param fromDir: The path to the VCS repository to export.
@type exportDir: L{twisted.python.filepath.FilePath}
@param exportDir: The directory to export the content of the
repository to. This directory doesn't have to exist prior to
exporting the repository. | exportTo | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | MIT |
def ensureIsWorkingDirectory(path):
"""
Ensure that C{path} is a Git working directory.
@type path: L{twisted.python.filepath.FilePath}
@param path: The path to check.
"""
try:
runCommand(["git", "rev-parse"], cwd=path.path)
except (CalledProcessError, OSError):
raise NotWorkingDirectory(
"%s does not appear to be a Git repository."
% (path.path,)) | Ensure that C{path} is a Git working directory.
@type path: L{twisted.python.filepath.FilePath}
@param path: The path to check. | ensureIsWorkingDirectory | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | MIT |
def remove(path):
"""
Remove the specified path from a Git repository.
@type path: L{twisted.python.filepath.FilePath}
@param path: The path to remove from the repository.
"""
runCommand(["git", "-C", path.dirname(), "rm", path.path]) | Remove the specified path from a Git repository.
@type path: L{twisted.python.filepath.FilePath}
@param path: The path to remove from the repository. | remove | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | MIT |
def exportTo(fromDir, exportDir):
"""
Export the content of a Git repository to the specified directory.
@type fromDir: L{twisted.python.filepath.FilePath}
@param fromDir: The path to the Git repository to export.
@type exportDir: L{twisted.python.filepath.FilePath}
@param exportDir: The directory to export the content of the
repository to. This directory doesn't have to exist prior to
exporting the repository.
"""
runCommand(["git", "-C", fromDir.path,
"checkout-index", "--all", "--force",
# prefix has to end up with a "/" so that files get copied
# to a directory whose name is the prefix.
"--prefix", exportDir.path + "/"]) | Export the content of a Git repository to the specified directory.
@type fromDir: L{twisted.python.filepath.FilePath}
@param fromDir: The path to the Git repository to export.
@type exportDir: L{twisted.python.filepath.FilePath}
@param exportDir: The directory to export the content of the
repository to. This directory doesn't have to exist prior to
exporting the repository. | exportTo | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | MIT |
def getRepositoryCommand(directory):
"""
Detect the VCS used in the specified directory and return a L{GitCommand}
if the directory is a Git repository. If the directory is not git, it
raises a L{NotWorkingDirectory} exception.
@type directory: L{FilePath}
@param directory: The directory to detect the VCS used from.
@rtype: L{GitCommand}
@raise NotWorkingDirectory: if no supported VCS can be found from the
specified directory.
"""
try:
GitCommand.ensureIsWorkingDirectory(directory)
return GitCommand
except (NotWorkingDirectory, OSError):
# It's not Git, but that's okay, eat the error
pass
raise NotWorkingDirectory("No supported VCS can be found in %s" %
(directory.path,)) | Detect the VCS used in the specified directory and return a L{GitCommand}
if the directory is a Git repository. If the directory is not git, it
raises a L{NotWorkingDirectory} exception.
@type directory: L{FilePath}
@param directory: The directory to detect the VCS used from.
@rtype: L{GitCommand}
@raise NotWorkingDirectory: if no supported VCS can be found from the
specified directory. | getRepositoryCommand | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | MIT |
def getVersion(self):
"""
@return: A L{incremental.Version} specifying the version number of the
project based on live python modules.
"""
namespace = {}
directory = self.directory
while not namespace:
if directory.path == "/":
raise Exception("Not inside a Twisted project.")
elif not directory.basename() == "twisted":
directory = directory.parent()
else:
execfile(directory.child("_version.py").path, namespace)
return namespace["__version__"] | @return: A L{incremental.Version} specifying the version number of the
project based on live python modules. | getVersion | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | MIT |
def findTwistedProjects(baseDirectory):
"""
Find all Twisted-style projects beneath a base directory.
@param baseDirectory: A L{twisted.python.filepath.FilePath} to look inside.
@return: A list of L{Project}.
"""
projects = []
for filePath in baseDirectory.walk():
if filePath.basename() == 'newsfragments':
projectDirectory = filePath.parent()
projects.append(Project(projectDirectory))
return projects | Find all Twisted-style projects beneath a base directory.
@param baseDirectory: A L{twisted.python.filepath.FilePath} to look inside.
@return: A list of L{Project}. | findTwistedProjects | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | MIT |
def replaceInFile(filename, oldToNew):
"""
I replace the text `oldstr' with `newstr' in `filename' using science.
"""
os.rename(filename, filename + '.bak')
with open(filename + '.bak') as f:
d = f.read()
for k, v in oldToNew.items():
d = d.replace(k, v)
with open(filename + '.new', 'w') as f:
f.write(d)
os.rename(filename + '.new', filename)
os.unlink(filename + '.bak') | I replace the text `oldstr' with `newstr' in `filename' using science. | replaceInFile | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | MIT |
def build(self, projectName, projectURL, sourceURL, packagePath,
outputPath):
"""
Call pydoctor's entry point with options which will generate HTML
documentation for the specified package's API.
@type projectName: C{str}
@param projectName: The name of the package for which to generate
documentation.
@type projectURL: C{str}
@param projectURL: The location (probably an HTTP URL) of the project
on the web.
@type sourceURL: C{str}
@param sourceURL: The location (probably an HTTP URL) of the root of
the source browser for the project.
@type packagePath: L{FilePath}
@param packagePath: The path to the top-level of the package named by
C{projectName}.
@type outputPath: L{FilePath}
@param outputPath: An existing directory to which the generated API
documentation will be written.
"""
intersphinxes = []
for intersphinx in intersphinxURLs:
intersphinxes.append("--intersphinx")
intersphinxes.append(intersphinx)
# Super awful monkeypatch that will selectively use our templates.
from pydoctor.templatewriter import util
originalTemplatefile = util.templatefile
def templatefile(filename):
if filename in ["summary.html", "index.html", "common.html"]:
twistedPythonDir = FilePath(__file__).parent()
templatesDir = twistedPythonDir.child("_pydoctortemplates")
return templatesDir.child(filename).path
else:
return originalTemplatefile(filename)
monkeyPatch = MonkeyPatcher((util, "templatefile", templatefile))
monkeyPatch.patch()
from pydoctor.driver import main
args = [u"--project-name", projectName,
u"--project-url", projectURL,
u"--system-class", u"twisted.python._pydoctor.TwistedSystem",
u"--project-base-dir", packagePath.parent().path,
u"--html-viewsource-base", sourceURL,
u"--add-package", packagePath.path,
u"--html-output", outputPath.path,
u"--html-write-function-pages", u"--quiet", u"--make-html",
] + intersphinxes
args = [arg.encode("utf-8") for arg in args]
main(args)
monkeyPatch.restore() | Call pydoctor's entry point with options which will generate HTML
documentation for the specified package's API.
@type projectName: C{str}
@param projectName: The name of the package for which to generate
documentation.
@type projectURL: C{str}
@param projectURL: The location (probably an HTTP URL) of the project
on the web.
@type sourceURL: C{str}
@param sourceURL: The location (probably an HTTP URL) of the root of
the source browser for the project.
@type packagePath: L{FilePath}
@param packagePath: The path to the top-level of the package named by
C{projectName}.
@type outputPath: L{FilePath}
@param outputPath: An existing directory to which the generated API
documentation will be written. | build | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | MIT |
def main(self, args):
"""
Build the main documentation.
@type args: list of str
@param args: The command line arguments to process. This must contain
one string argument: the path to the root of a Twisted checkout.
Additional arguments will be ignored for compatibility with legacy
build infrastructure.
"""
output = self.build(FilePath(args[0]).child("docs"))
if output:
sys.stdout.write(u"Unclean build:\n{}\n".format(output))
raise sys.exit(1) | Build the main documentation.
@type args: list of str
@param args: The command line arguments to process. This must contain
one string argument: the path to the root of a Twisted checkout.
Additional arguments will be ignored for compatibility with legacy
build infrastructure. | main | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | MIT |
def build(self, docDir, buildDir=None, version=''):
"""
Build the documentation in C{docDir} with Sphinx.
@param docDir: The directory of the documentation. This is a directory
which contains another directory called "source" which contains the
Sphinx "conf.py" file and sphinx source documents.
@type docDir: L{twisted.python.filepath.FilePath}
@param buildDir: The directory to build the documentation in. By
default this will be a child directory of {docDir} named "build".
@type buildDir: L{twisted.python.filepath.FilePath}
@param version: The version of Twisted to set in the docs.
@type version: C{str}
@return: the output produced by running the command
@rtype: L{str}
"""
if buildDir is None:
buildDir = docDir.parent().child('doc')
doctreeDir = buildDir.child('doctrees')
output = runCommand(['sphinx-build', '-q', '-b', 'html',
'-d', doctreeDir.path, docDir.path,
buildDir.path]).decode("utf-8")
# Delete the doctrees, as we don't want them after the docs are built
doctreeDir.remove()
for path in docDir.walk():
if path.basename() == "man":
segments = path.segmentsFrom(docDir)
dest = buildDir
while segments:
dest = dest.child(segments.pop(0))
if not dest.parent().isdir():
dest.parent().makedirs()
path.copyTo(dest)
return output | Build the documentation in C{docDir} with Sphinx.
@param docDir: The directory of the documentation. This is a directory
which contains another directory called "source" which contains the
Sphinx "conf.py" file and sphinx source documents.
@type docDir: L{twisted.python.filepath.FilePath}
@param buildDir: The directory to build the documentation in. By
default this will be a child directory of {docDir} named "build".
@type buildDir: L{twisted.python.filepath.FilePath}
@param version: The version of Twisted to set in the docs.
@type version: C{str}
@return: the output produced by running the command
@rtype: L{str} | build | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | MIT |
def filePathDelta(origin, destination):
"""
Return a list of strings that represent C{destination} as a path relative
to C{origin}.
It is assumed that both paths represent directories, not files. That is to
say, the delta of L{twisted.python.filepath.FilePath} /foo/bar to
L{twisted.python.filepath.FilePath} /foo/baz will be C{../baz},
not C{baz}.
@type origin: L{twisted.python.filepath.FilePath}
@param origin: The origin of the relative path.
@type destination: L{twisted.python.filepath.FilePath}
@param destination: The destination of the relative path.
"""
commonItems = 0
path1 = origin.path.split(os.sep)
path2 = destination.path.split(os.sep)
for elem1, elem2 in zip(path1, path2):
if elem1 == elem2:
commonItems += 1
else:
break
path = [".."] * (len(path1) - commonItems)
return path + path2[commonItems:] | Return a list of strings that represent C{destination} as a path relative
to C{origin}.
It is assumed that both paths represent directories, not files. That is to
say, the delta of L{twisted.python.filepath.FilePath} /foo/bar to
L{twisted.python.filepath.FilePath} /foo/baz will be C{../baz},
not C{baz}.
@type origin: L{twisted.python.filepath.FilePath}
@param origin: The origin of the relative path.
@type destination: L{twisted.python.filepath.FilePath}
@param destination: The destination of the relative path. | filePathDelta | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | MIT |
def buildAPIDocs(self, projectRoot, output):
"""
Build the API documentation of Twisted, with our project policy.
@param projectRoot: A L{FilePath} representing the root of the Twisted
checkout.
@param output: A L{FilePath} pointing to the desired output directory.
"""
version = Project(
projectRoot.child("twisted")).getVersion()
versionString = version.base()
sourceURL = ("https://github.com/twisted/twisted/tree/"
"twisted-%s" % (versionString,) + "/src")
apiBuilder = APIBuilder()
apiBuilder.build(
"Twisted",
"http://twistedmatrix.com/",
sourceURL,
projectRoot.child("twisted"),
output) | Build the API documentation of Twisted, with our project policy.
@param projectRoot: A L{FilePath} representing the root of the Twisted
checkout.
@param output: A L{FilePath} pointing to the desired output directory. | buildAPIDocs | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | MIT |
def main(self, args):
"""
Build API documentation.
@type args: list of str
@param args: The command line arguments to process. This must contain
two strings: the path to the root of the Twisted checkout, and a
path to an output directory.
"""
if len(args) != 2:
sys.exit("Must specify two arguments: "
"Twisted checkout and destination path")
self.buildAPIDocs(FilePath(args[0]), FilePath(args[1])) | Build API documentation.
@type args: list of str
@param args: The command line arguments to process. This must contain
two strings: the path to the root of the Twisted checkout, and a
path to an output directory. | main | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | MIT |
def main(self, args):
"""
Run the script.
@type args: L{list} of L{str}
@param args: The command line arguments to process. This must contain
one string: the path to the root of the Twisted checkout.
"""
if len(args) != 1:
sys.exit("Must specify one argument: the Twisted checkout")
encoding = sys.stdout.encoding or 'ascii'
location = os.path.abspath(args[0])
branch = runCommand([b"git", b"rev-parse", b"--abbrev-ref", "HEAD"],
cwd=location).decode(encoding).strip()
r = runCommand([b"git", b"diff", b"--name-only", b"origin/trunk..."],
cwd=location).decode(encoding).strip()
if not r:
self._print(
"On trunk or no diffs from trunk; no need to look at this.")
sys.exit(0)
files = r.strip().split(os.linesep)
self._print("Looking at these files:")
for change in files:
self._print(change)
self._print("----")
if len(files) == 1:
if files[0] == os.sep.join(["docs", "fun", "Twisted.Quotes"]):
self._print("Quotes change only; no newsfragment needed.")
sys.exit(0)
newsfragments = []
for change in files:
if os.sep + "newsfragments" + os.sep in change:
if "." in change and change.rsplit(".", 1)[1] in NEWSFRAGMENT_TYPES:
newsfragments.append(change)
if branch.startswith("release-"):
if newsfragments:
self._print("No newsfragments should be on the release branch.")
sys.exit(1)
else:
self._print("Release branch with no newsfragments, all good.")
sys.exit(0)
for change in newsfragments:
self._print("Found " + change)
sys.exit(0)
self._print("No newsfragment found. Have you committed it?")
sys.exit(1) | Run the script.
@type args: L{list} of L{str}
@param args: The command line arguments to process. This must contain
one string: the path to the root of the Twisted checkout. | main | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_release.py | MIT |
def cmdLineQuote(s):
"""
Internal method for quoting a single command-line argument.
@param s: an unquoted string that you want to quote so that something that
does cmd.exe-style unquoting will interpret it as a single argument,
even if it contains spaces.
@type s: C{str}
@return: a quoted string.
@rtype: C{str}
"""
quote = ((" " in s) or ("\t" in s) or ('"' in s) or s == '') and '"' or ''
return quote + _cmdLineQuoteRe2.sub(r"\1\1", _cmdLineQuoteRe.sub(r'\1\1\\"', s)) + quote | Internal method for quoting a single command-line argument.
@param s: an unquoted string that you want to quote so that something that
does cmd.exe-style unquoting will interpret it as a single argument,
even if it contains spaces.
@type s: C{str}
@return: a quoted string.
@rtype: C{str} | cmdLineQuote | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/win32.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/win32.py | MIT |
def quoteArguments(arguments):
"""
Quote an iterable of command-line arguments for passing to CreateProcess or
a similar API. This allows the list passed to C{reactor.spawnProcess} to
match the child process's C{sys.argv} properly.
@param arglist: an iterable of C{str}, each unquoted.
@return: a single string, with the given sequence quoted as necessary.
"""
return ' '.join([cmdLineQuote(a) for a in arguments]) | Quote an iterable of command-line arguments for passing to CreateProcess or
a similar API. This allows the list passed to C{reactor.spawnProcess} to
match the child process's C{sys.argv} properly.
@param arglist: an iterable of C{str}, each unquoted.
@return: a single string, with the given sequence quoted as necessary. | quoteArguments | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/win32.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/win32.py | MIT |
def fromEnvironment(cls):
"""
Get as many of the platform-specific error translation objects as
possible and return an instance of C{cls} created with them.
"""
try:
from ctypes import WinError
except ImportError:
WinError = None
try:
from win32api import FormatMessage
except ImportError:
FormatMessage = None
try:
from socket import errorTab
except ImportError:
errorTab = None
return cls(WinError, FormatMessage, errorTab) | Get as many of the platform-specific error translation objects as
possible and return an instance of C{cls} created with them. | fromEnvironment | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/win32.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/win32.py | MIT |
def formatError(self, errorcode):
"""
Returns the string associated with a Windows error message, such as the
ones found in socket.error.
Attempts direct lookup against the win32 API via ctypes and then
pywin32 if available), then in the error table in the socket module,
then finally defaulting to C{os.strerror}.
@param errorcode: the Windows error code
@type errorcode: C{int}
@return: The error message string
@rtype: C{str}
"""
if self.winError is not None:
return self.winError(errorcode).strerror
if self.formatMessage is not None:
return self.formatMessage(errorcode)
if self.errorTab is not None:
result = self.errorTab.get(errorcode)
if result is not None:
return result
return os.strerror(errorcode) | Returns the string associated with a Windows error message, such as the
ones found in socket.error.
Attempts direct lookup against the win32 API via ctypes and then
pywin32 if available), then in the error table in the socket module,
then finally defaulting to C{os.strerror}.
@param errorcode: the Windows error code
@type errorcode: C{int}
@return: The error message string
@rtype: C{str} | formatError | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/win32.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/win32.py | MIT |
def __init__(self, options, coerce):
"""
@param options: parent Options object
@param coerce: callable used to coerce the value.
"""
self.options = options
self.coerce = coerce
self.doc = getattr(self.coerce, 'coerceDoc', '') | @param options: parent Options object
@param coerce: callable used to coerce the value. | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/usage.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/usage.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.