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
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
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 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.)
"""
status = runCommand(
["git", "-C", path.path, "status", "--short"]).strip()
return status == b'' | 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 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 |
def dispatch(self, parameterName, value):
"""
When called in dispatch, do the coerce for C{value} and save the
returned value.
"""
if value is None:
raise UsageError("Parameter '%s' requires an argument."
% (parameterName,))
try:
value = self.coerce(value)
except ValueError as e:
raise UsageError("Parameter type enforcement failed: %s" % (e,))
self.options.opts[parameterName] = value | When called in dispatch, do the coerce for C{value} and save the
returned value. | dispatch | 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 |
def opt_help(self):
"""
Display this help and exit.
"""
print(self.__str__())
sys.exit(0) | Display this help and exit. | opt_help | 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 |
def opt_version(self):
"""
Display Twisted version and exit.
"""
from twisted import copyright
print("Twisted version:", copyright.version)
sys.exit(0) | Display Twisted version and exit. | opt_version | 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 |
def parseOptions(self, options=None):
"""
The guts of the command-line parser.
"""
if options is None:
options = sys.argv[1:]
# we really do need to place the shell completion check here, because
# if we used an opt_shell_completion method then it would be possible
# for other opt_* methods to be run first, and they could possibly
# raise validation errors which would result in error output on the
# terminal of the user performing shell completion. Validation errors
# would occur quite frequently, in fact, because users often initiate
# tab-completion while they are editing an unfinished command-line.
if len(options) > 1 and options[-2] == "--_shell-completion":
from twisted.python import _shellcomp
cmdName = path.basename(sys.argv[0])
_shellcomp.shellComplete(self, cmdName, options,
self._shellCompFile)
sys.exit(0)
try:
opts, args = getopt.getopt(options,
self.shortOpt, self.longOpt)
except getopt.error as e:
raise UsageError(str(e))
for opt, arg in opts:
if opt[1] == '-':
opt = opt[2:]
else:
opt = opt[1:]
optMangled = opt
if optMangled not in self.synonyms:
optMangled = opt.replace("-", "_")
if optMangled not in self.synonyms:
raise UsageError("No such option '%s'" % (opt,))
optMangled = self.synonyms[optMangled]
if isinstance(self._dispatch[optMangled], CoerceParameter):
self._dispatch[optMangled].dispatch(optMangled, arg)
else:
self._dispatch[optMangled](optMangled, arg)
if (getattr(self, 'subCommands', None)
and (args or self.defaultSubCommand is not None)):
if not args:
args = [self.defaultSubCommand]
sub, rest = args[0], args[1:]
for (cmd, short, parser, doc) in self.subCommands:
if sub == cmd or sub == short:
self.subCommand = cmd
self.subOptions = parser()
self.subOptions.parent = self
self.subOptions.parseOptions(rest)
break
else:
raise UsageError("Unknown command: %s" % sub)
else:
try:
self.parseArgs(*args)
except TypeError:
raise UsageError("Wrong number of arguments.")
self.postOptions() | The guts of the command-line parser. | parseOptions | 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 |
def postOptions(self):
"""
I am called after the options are parsed.
Override this method in your subclass to do something after
the options have been parsed and assigned, like validate that
all options are sane.
""" | I am called after the options are parsed.
Override this method in your subclass to do something after
the options have been parsed and assigned, like validate that
all options are sane. | postOptions | 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 |
def parseArgs(self):
"""
I am called with any leftover arguments which were not options.
Override me to do something with the remaining arguments on
the command line, those which were not flags or options. e.g.
interpret them as a list of files to operate on.
Note that if there more arguments on the command line
than this method accepts, parseArgs will blow up with
a getopt.error. This means if you don't override me,
parseArgs will blow up if I am passed any arguments at
all!
""" | I am called with any leftover arguments which were not options.
Override me to do something with the remaining arguments on
the command line, those which were not flags or options. e.g.
interpret them as a list of files to operate on.
Note that if there more arguments on the command line
than this method accepts, parseArgs will blow up with
a getopt.error. This means if you don't override me,
parseArgs will blow up if I am passed any arguments at
all! | parseArgs | 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 |
def _gather_flags(self):
"""
Gather up boolean (flag) options.
"""
longOpt, shortOpt = [], ''
docs, settings, synonyms, dispatch = {}, {}, {}, {}
flags = []
reflect.accumulateClassList(self.__class__, 'optFlags', flags)
for flag in flags:
long, short, doc = util.padTo(3, flag)
if not long:
raise ValueError("A flag cannot be without a name.")
docs[long] = doc
settings[long] = 0
if short:
shortOpt = shortOpt + short
synonyms[short] = long
longOpt.append(long)
synonyms[long] = long
dispatch[long] = self._generic_flag
return longOpt, shortOpt, docs, settings, synonyms, dispatch | Gather up boolean (flag) options. | _gather_flags | 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 |
def _gather_parameters(self):
"""
Gather options which take a value.
"""
longOpt, shortOpt = [], ''
docs, settings, synonyms, dispatch = {}, {}, {}, {}
parameters = []
reflect.accumulateClassList(self.__class__, 'optParameters',
parameters)
synonyms = {}
for parameter in parameters:
long, short, default, doc, paramType = util.padTo(5, parameter)
if not long:
raise ValueError("A parameter cannot be without a name.")
docs[long] = doc
settings[long] = default
if short:
shortOpt = shortOpt + short + ':'
synonyms[short] = long
longOpt.append(long + '=')
synonyms[long] = long
if paramType is not None:
dispatch[long] = CoerceParameter(self, paramType)
else:
dispatch[long] = CoerceParameter(self, str)
return longOpt, shortOpt, docs, settings, synonyms, dispatch | Gather options which take a value. | _gather_parameters | 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 |
def _gather_handlers(self):
"""
Gather up options with their own handler methods.
This returns a tuple of many values. Amongst those values is a
synonyms dictionary, mapping all of the possible aliases (C{str})
for an option to the longest spelling of that option's name
C({str}).
Another element is a dispatch dictionary, mapping each user-facing
option name (with - substituted for _) to a callable to handle that
option.
"""
longOpt, shortOpt = [], ''
docs, settings, synonyms, dispatch = {}, {}, {}, {}
dct = {}
reflect.addMethodNamesToDict(self.__class__, dct, "opt_")
for name in dct.keys():
method = getattr(self, 'opt_'+name)
takesArg = not flagFunction(method, name)
prettyName = name.replace('_', '-')
doc = getattr(method, '__doc__', None)
if doc:
## Only use the first line.
#docs[name] = doc.split('\n')[0]
docs[prettyName] = doc
else:
docs[prettyName] = self.docs.get(prettyName)
synonyms[prettyName] = prettyName
# A little slight-of-hand here makes dispatching much easier
# in parseOptions, as it makes all option-methods have the
# same signature.
if takesArg:
fn = lambda name, value, m=method: m(value)
else:
# XXX: This won't raise a TypeError if it's called
# with a value when it shouldn't be.
fn = lambda name, value=None, m=method: m()
dispatch[prettyName] = fn
if len(name) == 1:
shortOpt = shortOpt + name
if takesArg:
shortOpt = shortOpt + ':'
else:
if takesArg:
prettyName = prettyName + '='
longOpt.append(prettyName)
reverse_dct = {}
# Map synonyms
for name in dct.keys():
method = getattr(self, 'opt_' + name)
if method not in reverse_dct:
reverse_dct[method] = []
reverse_dct[method].append(name.replace('_', '-'))
for method, names in reverse_dct.items():
if len(names) < 2:
continue
longest = max(names, key=len)
for name in names:
synonyms[name] = longest
return longOpt, shortOpt, docs, settings, synonyms, dispatch | Gather up options with their own handler methods.
This returns a tuple of many values. Amongst those values is a
synonyms dictionary, mapping all of the possible aliases (C{str})
for an option to the longest spelling of that option's name
C({str}).
Another element is a dispatch dictionary, mapping each user-facing
option name (with - substituted for _) to a callable to handle that
option. | _gather_handlers | 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 |
def getSynopsis(self):
"""
Returns a string containing a description of these options and how to
pass them to the executed file.
"""
executableName = reflect.filenameToModuleName(sys.argv[0])
if executableName.endswith('.__main__'):
executableName = '{} -m {}'.format(os.path.basename(sys.executable), executableName.replace('.__main__', ''))
if self.parent is None:
default = "Usage: %s%s" % (executableName,
(self.longOpt and " [options]") or '')
else:
default = '%s' % ((self.longOpt and "[options]") or '')
synopsis = getattr(self, "synopsis", default)
synopsis = synopsis.rstrip()
if self.parent is not None:
synopsis = ' '.join((self.parent.getSynopsis(),
self.parent.subCommand, synopsis))
return synopsis | Returns a string containing a description of these options and how to
pass them to the executed file. | getSynopsis | 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 |
def __init__(self, descr=None, repeat=False):
"""
@type descr: C{str}
@param descr: An optional descriptive string displayed above matches.
@type repeat: C{bool}
@param repeat: A flag, defaulting to False, indicating whether this
C{Completer} should repeat - that is, be used to complete more
than one command-line word. This may ONLY be set to True for
actions in the C{extraActions} keyword argument to C{Completions}.
And ONLY if it is the LAST (or only) action in the C{extraActions}
list.
"""
if descr is not None:
self._descr = descr
self._repeat = repeat | @type descr: C{str}
@param descr: An optional descriptive string displayed above matches.
@type repeat: C{bool}
@param repeat: A flag, defaulting to False, indicating whether this
C{Completer} should repeat - that is, be used to complete more
than one command-line word. This may ONLY be set to True for
actions in the C{extraActions} keyword argument to C{Completions}.
And ONLY if it is the LAST (or only) action in the C{extraActions}
list. | __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 |
def _shellCode(self, optName, shellType):
"""
Fetch a fragment of shell code representing this action which is
suitable for use by the completion system in _shellcomp.py
@type optName: C{str}
@param optName: The long name of the option this action is being
used for.
@type shellType: C{str}
@param shellType: One of the supported shell constants e.g.
C{twisted.python.usage._ZSH}
"""
if shellType == _ZSH:
return "%s:%s:" % (self._repeatFlag,
self._description(optName))
raise NotImplementedError("Unknown shellType %r" % (shellType,)) | Fetch a fragment of shell code representing this action which is
suitable for use by the completion system in _shellcomp.py
@type optName: C{str}
@param optName: The long name of the option this action is being
used for.
@type shellType: C{str}
@param shellType: One of the supported shell constants e.g.
C{twisted.python.usage._ZSH} | _shellCode | 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 |
def docMakeChunks(optList, width=80):
"""
Makes doc chunks for option declarations.
Takes a list of dictionaries, each of which may have one or more
of the keys 'long', 'short', 'doc', 'default', 'optType'.
Returns a list of strings.
The strings may be multiple lines,
all of them end with a newline.
"""
# XXX: sanity check to make sure we have a sane combination of keys.
# Sort the options so they always appear in the same order
optList.sort(key=lambda o: o.get('short', None) or o.get('long', None))
maxOptLen = 0
for opt in optList:
optLen = len(opt.get('long', ''))
if optLen:
if opt.get('optType', None) == "parameter":
# these take up an extra character
optLen = optLen + 1
maxOptLen = max(optLen, maxOptLen)
colWidth1 = maxOptLen + len(" -s, -- ")
colWidth2 = width - colWidth1
# XXX - impose some sane minimum limit.
# Then if we don't have enough room for the option and the doc
# to share one line, they can take turns on alternating lines.
colFiller1 = " " * colWidth1
optChunks = []
seen = {}
for opt in optList:
if opt.get('short', None) in seen or opt.get('long', None) in seen:
continue
for x in opt.get('short', None), opt.get('long', None):
if x is not None:
seen[x] = 1
optLines = []
comma = " "
if opt.get('short', None):
short = "-%c" % (opt['short'],)
else:
short = ''
if opt.get('long', None):
long = opt['long']
if opt.get("optType", None) == "parameter":
long = long + '='
long = "%-*s" % (maxOptLen, long)
if short:
comma = ","
else:
long = " " * (maxOptLen + len('--'))
if opt.get('optType', None) == 'command':
column1 = ' %s ' % long
else:
column1 = " %2s%c --%s " % (short, comma, long)
if opt.get('doc', ''):
doc = opt['doc'].strip()
else:
doc = ''
if (opt.get("optType", None) == "parameter") \
and not (opt.get('default', None) is None):
doc = "%s [default: %s]" % (doc, opt['default'])
if (opt.get("optType", None) == "parameter") \
and opt.get('dispatch', None) is not None:
d = opt['dispatch']
if isinstance(d, CoerceParameter) and d.doc:
doc = "%s. %s" % (doc, d.doc)
if doc:
column2_l = textwrap.wrap(doc, colWidth2)
else:
column2_l = ['']
optLines.append("%s%s\n" % (column1, column2_l.pop(0)))
for line in column2_l:
optLines.append("%s%s\n" % (colFiller1, line))
optChunks.append(''.join(optLines))
return optChunks | Makes doc chunks for option declarations.
Takes a list of dictionaries, each of which may have one or more
of the keys 'long', 'short', 'doc', 'default', 'optType'.
Returns a list of strings.
The strings may be multiple lines,
all of them end with a newline. | docMakeChunks | 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 |
def flagFunction(method, name=None):
"""
Determine whether a function is an optional handler for a I{flag} or an
I{option}.
A I{flag} handler takes no additional arguments. It is used to handle
command-line arguments like I{--nodaemon}.
An I{option} handler takes one argument. It is used to handle command-line
arguments like I{--path=/foo/bar}.
@param method: The bound method object to inspect.
@param name: The name of the option for which the function is a handle.
@type name: L{str}
@raise UsageError: If the method takes more than one argument.
@return: If the method is a flag handler, return C{True}. Otherwise return
C{False}.
"""
if _PY3:
reqArgs = len(inspect.signature(method).parameters)
if reqArgs > 1:
raise UsageError('Invalid Option function for %s' %
(name or method.__name__))
if reqArgs == 1:
return False
else:
reqArgs = len(inspect.getargspec(method).args)
if reqArgs > 2:
raise UsageError('Invalid Option function for %s' %
(name or method.__name__))
if reqArgs == 2:
return False
return True | Determine whether a function is an optional handler for a I{flag} or an
I{option}.
A I{flag} handler takes no additional arguments. It is used to handle
command-line arguments like I{--nodaemon}.
An I{option} handler takes one argument. It is used to handle command-line
arguments like I{--path=/foo/bar}.
@param method: The bound method object to inspect.
@param name: The name of the option for which the function is a handle.
@type name: L{str}
@raise UsageError: If the method takes more than one argument.
@return: If the method is a flag handler, return C{True}. Otherwise return
C{False}. | flagFunction | 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 |
def portCoerce(value):
"""
Coerce a string value to an int port number, and checks the validity.
"""
value = int(value)
if value < 0 or value > 65535:
raise ValueError("Port number not in range: %s" % (value,))
return value | Coerce a string value to an int port number, and checks the validity. | portCoerce | 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 |
def coerce(self, val):
"""Convert the value to the correct format."""
raise NotImplementedError("implement in subclass") | Convert the value to the correct format. | coerce | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/formmethod.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/formmethod.py | MIT |
def coerce(self, args):
"""Return tuple of ints (year, month, day)."""
if tuple(args) == ("", "", "") and self.allowNone:
return None
try:
year, month, day = map(positiveInt, args)
except ValueError:
raise InputError("Invalid date")
if (month, day) == (2, 29):
if not calendar.isleap(year):
raise InputError("%d was not a leap year" % year)
else:
return year, month, day
try:
mdays = calendar.mdays[month]
except IndexError:
raise InputError("Invalid date")
if day > mdays:
raise InputError("Invalid date")
return year, month, day | Return tuple of ints (year, month, day). | coerce | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/formmethod.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/formmethod.py | MIT |
def __init__(self, dict=None, preserve=1):
"""
Create an empty dictionary, or update from 'dict'.
"""
self.data = {}
self.preserve=preserve
if dict:
self.update(dict) | Create an empty dictionary, or update from 'dict'. | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def __getitem__(self, key):
"""
Retrieve the value associated with 'key' (in any case).
"""
k = self._lowerOrReturn(key)
return self.data[k][1] | Retrieve the value associated with 'key' (in any case). | __getitem__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def __setitem__(self, key, value):
"""
Associate 'value' with 'key'. If 'key' already exists, but
in different case, it will be replaced.
"""
k = self._lowerOrReturn(key)
self.data[k] = (key, value) | Associate 'value' with 'key'. If 'key' already exists, but
in different case, it will be replaced. | __setitem__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def has_key(self, key):
"""
Case insensitive test whether 'key' exists.
"""
k = self._lowerOrReturn(key)
return k in self.data | Case insensitive test whether 'key' exists. | has_key | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def keys(self):
"""
List of keys in their original case.
"""
return list(self.iterkeys()) | List of keys in their original case. | keys | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def values(self):
"""
List of values.
"""
return list(self.itervalues()) | List of values. | values | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def items(self):
"""
List of (key,value) pairs.
"""
return list(self.iteritems()) | List of (key,value) pairs. | items | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def get(self, key, default=None):
"""
Retrieve value associated with 'key' or return default value
if 'key' doesn't exist.
"""
try:
return self[key]
except KeyError:
return default | Retrieve value associated with 'key' or return default value
if 'key' doesn't exist. | get | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def setdefault(self, key, default):
"""
If 'key' doesn't exist, associate it with the 'default' value.
Return value associated with 'key'.
"""
if not self.has_key(key):
self[key] = default
return self[key] | If 'key' doesn't exist, associate it with the 'default' value.
Return value associated with 'key'. | setdefault | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def update(self, dict):
"""
Copy (key,value) pairs from 'dict'.
"""
for k,v in dict.items():
self[k] = v | Copy (key,value) pairs from 'dict'. | update | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def __repr__(self):
"""
String representation of the dictionary.
"""
items = ", ".join([("%r: %r" % (k,v)) for k,v in self.items()])
return "InsensitiveDict({%s})" % items | String representation of the dictionary. | __repr__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def uniquify(lst):
"""
Make the elements of a list unique by inserting them into a dictionary.
This must not change the order of the input lst.
"""
dct = {}
result = []
for k in lst:
if k not in dct:
result.append(k)
dct[k] = 1
return result | Make the elements of a list unique by inserting them into a dictionary.
This must not change the order of the input lst. | uniquify | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def padTo(n, seq, default=None):
"""
Pads a sequence out to n elements,
filling in with a default value if it is not long enough.
If the input sequence is longer than n, raises ValueError.
Details, details:
This returns a new list; it does not extend the original sequence.
The new list contains the values of the original sequence, not copies.
"""
if len(seq) > n:
raise ValueError("%d elements is more than %d." % (len(seq), n))
blank = [default] * n
blank[:len(seq)] = list(seq)
return blank | Pads a sequence out to n elements,
filling in with a default value if it is not long enough.
If the input sequence is longer than n, raises ValueError.
Details, details:
This returns a new list; it does not extend the original sequence.
The new list contains the values of the original sequence, not copies. | padTo | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def sibpath(path, sibling):
"""
Return the path to a sibling of a file in the filesystem.
This is useful in conjunction with the special C{__file__} attribute
that Python provides for modules, so modules can load associated
resource files.
"""
return os.path.join(os.path.dirname(os.path.abspath(path)), sibling) | Return the path to a sibling of a file in the filesystem.
This is useful in conjunction with the special C{__file__} attribute
that Python provides for modules, so modules can load associated
resource files. | sibpath | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def _getpass(prompt):
"""
Helper to turn IOErrors into KeyboardInterrupts.
"""
import getpass
try:
return getpass.getpass(prompt)
except IOError as e:
if e.errno == errno.EINTR:
raise KeyboardInterrupt
raise
except EOFError:
raise KeyboardInterrupt | Helper to turn IOErrors into KeyboardInterrupts. | _getpass | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def getPassword(prompt = 'Password: ', confirm = 0, forceTTY = 0,
confirmPrompt = 'Confirm password: ',
mismatchMessage = "Passwords don't match."):
"""
Obtain a password by prompting or from stdin.
If stdin is a terminal, prompt for a new password, and confirm (if
C{confirm} is true) by asking again to make sure the user typed the same
thing, as keystrokes will not be echoed.
If stdin is not a terminal, and C{forceTTY} is not true, read in a line
and use it as the password, less the trailing newline, if any. If
C{forceTTY} is true, attempt to open a tty and prompt for the password
using it. Raise a RuntimeError if this is not possible.
@returns: C{str}
"""
isaTTY = hasattr(sys.stdin, 'isatty') and sys.stdin.isatty()
old = None
try:
if not isaTTY:
if forceTTY:
try:
old = sys.stdin, sys.stdout
sys.stdin = sys.stdout = open('/dev/tty', 'r+')
except:
raise RuntimeError("Cannot obtain a TTY")
else:
password = sys.stdin.readline()
if password[-1] == '\n':
password = password[:-1]
return password
while 1:
try1 = _getpass(prompt)
if not confirm:
return try1
try2 = _getpass(confirmPrompt)
if try1 == try2:
return try1
else:
sys.stderr.write(mismatchMessage + "\n")
finally:
if old:
sys.stdin.close()
sys.stdin, sys.stdout = old | Obtain a password by prompting or from stdin.
If stdin is a terminal, prompt for a new password, and confirm (if
C{confirm} is true) by asking again to make sure the user typed the same
thing, as keystrokes will not be echoed.
If stdin is not a terminal, and C{forceTTY} is not true, read in a line
and use it as the password, less the trailing newline, if any. If
C{forceTTY} is true, attempt to open a tty and prompt for the password
using it. Raise a RuntimeError if this is not possible.
@returns: C{str} | getPassword | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def makeStatBar(width, maxPosition, doneChar = '=', undoneChar = '-', currentChar = '>'):
"""
Creates a function that will return a string representing a progress bar.
"""
aValue = width / float(maxPosition)
def statBar(position, force = 0, last = ['']):
assert len(last) == 1, "Don't mess with the last parameter."
done = int(aValue * position)
toDo = width - done - 2
result = "[%s%s%s]" % (doneChar * done, currentChar, undoneChar * toDo)
if force:
last[0] = result
return result
if result == last[0]:
return ''
last[0] = result
return result
statBar.__doc__ = """statBar(position, force = 0) -> '[%s%s%s]'-style progress bar
returned string is %d characters long, and the range goes from 0..%d.
The 'position' argument is where the '%s' will be drawn. If force is false,
'' will be returned instead if the resulting progress bar is identical to the
previously returned progress bar.
""" % (doneChar * 3, currentChar, undoneChar * 3, width, maxPosition, currentChar)
return statBar | Creates a function that will return a string representing a progress bar. | makeStatBar | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def spewer(frame, s, ignored):
"""
A trace function for sys.settrace that prints every function or method call.
"""
from twisted.python import reflect
if 'self' in frame.f_locals:
se = frame.f_locals['self']
if hasattr(se, '__class__'):
k = reflect.qual(se.__class__)
else:
k = reflect.qual(type(se))
print('method %s of %s at %s' % (
frame.f_code.co_name, k, id(se)))
else:
print('function %s in %s, line %s' % (
frame.f_code.co_name,
frame.f_code.co_filename,
frame.f_lineno)) | A trace function for sys.settrace that prints every function or method call. | spewer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def searchupwards(start, files=[], dirs=[]):
"""
Walk upwards from start, looking for a directory containing
all files and directories given as arguments::
>>> searchupwards('.', ['foo.txt'], ['bar', 'bam'])
If not found, return None
"""
start=os.path.abspath(start)
parents=start.split(os.sep)
exists=os.path.exists; join=os.sep.join; isdir=os.path.isdir
while len(parents):
candidate=join(parents)+os.sep
allpresent=1
for f in files:
if not exists("%s%s" % (candidate, f)):
allpresent=0
break
if allpresent:
for d in dirs:
if not isdir("%s%s" % (candidate, d)):
allpresent=0
break
if allpresent: return candidate
parents.pop(-1)
return None | Walk upwards from start, looking for a directory containing
all files and directories given as arguments::
>>> searchupwards('.', ['foo.txt'], ['bar', 'bam'])
If not found, return None | searchupwards | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def __init__(self, size=10):
"""
Create a new log, with size lines of storage (default 10).
A log size of 0 (or less) means an infinite log.
"""
if size < 0:
size = 0
self.log = [None] * size
self.size = size | Create a new log, with size lines of storage (default 10).
A log size of 0 (or less) means an infinite log. | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def clear(self):
"""
Empty the log.
"""
self.log = [None] * self.size | Empty the log. | clear | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def raises(exception, f, *args, **kwargs):
"""
Determine whether the given call raises the given exception.
"""
try:
f(*args, **kwargs)
except exception:
return 1
return 0 | Determine whether the given call raises the given exception. | raises | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def __init__(self, intervals, default=60):
"""
@type intervals: C{list} of C{int}, C{long}, or C{float} param
@param intervals: The intervals between instants.
@type default: C{int}, C{long}, or C{float}
@param default: The duration to generate if the intervals list
becomes empty.
"""
self.intervals = intervals[:]
self.default = default | @type intervals: C{list} of C{int}, C{long}, or C{float} param
@param intervals: The intervals between instants.
@type default: C{int}, C{long}, or C{float}
@param default: The duration to generate if the intervals list
becomes empty. | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def initgroups(uid, primaryGid):
"""
Do nothing.
Underlying platform support require to manipulate groups is missing.
""" | Do nothing.
Underlying platform support require to manipulate groups is missing. | initgroups | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def initgroups(uid, primaryGid):
"""
Initializes the group access list.
This uses the stdlib support which calls initgroups(3) under the hood.
If the given user is a member of more than C{NGROUPS}, arbitrary
groups will be silently discarded to bring the number below that
limit.
@type uid: C{int}
@param uid: The UID for which to look up group information.
@type primaryGid: C{int}
@param primaryGid: The GID to include when setting the groups.
"""
return _initgroups(pwd.getpwuid(uid).pw_name, primaryGid) | Initializes the group access list.
This uses the stdlib support which calls initgroups(3) under the hood.
If the given user is a member of more than C{NGROUPS}, arbitrary
groups will be silently discarded to bring the number below that
limit.
@type uid: C{int}
@param uid: The UID for which to look up group information.
@type primaryGid: C{int}
@param primaryGid: The GID to include when setting the groups. | initgroups | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def switchUID(uid, gid, euid=False):
"""
Attempts to switch the uid/euid and gid/egid for the current process.
If C{uid} is the same value as L{os.getuid} (or L{os.geteuid}),
this function will issue a L{UserWarning} and not raise an exception.
@type uid: C{int} or L{None}
@param uid: the UID (or EUID) to switch the current process to. This
parameter will be ignored if the value is L{None}.
@type gid: C{int} or L{None}
@param gid: the GID (or EGID) to switch the current process to. This
parameter will be ignored if the value is L{None}.
@type euid: C{bool}
@param euid: if True, set only effective user-id rather than real user-id.
(This option has no effect unless the process is running
as root, in which case it means not to shed all
privileges, retaining the option to regain privileges
in cases such as spawning processes. Use with caution.)
"""
if euid:
setuid = os.seteuid
setgid = os.setegid
getuid = os.geteuid
else:
setuid = os.setuid
setgid = os.setgid
getuid = os.getuid
if gid is not None:
setgid(gid)
if uid is not None:
if uid == getuid():
uidText = (euid and "euid" or "uid")
actionText = "tried to drop privileges and set{} {}".format(
uidText, uid)
problemText = "{} is already {}".format(uidText, getuid())
warnings.warn("{} but {}; should we be root? Continuing.".format(
actionText, problemText))
else:
initgroups(uid, gid)
setuid(uid) | Attempts to switch the uid/euid and gid/egid for the current process.
If C{uid} is the same value as L{os.getuid} (or L{os.geteuid}),
this function will issue a L{UserWarning} and not raise an exception.
@type uid: C{int} or L{None}
@param uid: the UID (or EUID) to switch the current process to. This
parameter will be ignored if the value is L{None}.
@type gid: C{int} or L{None}
@param gid: the GID (or EGID) to switch the current process to. This
parameter will be ignored if the value is L{None}.
@type euid: C{bool}
@param euid: if True, set only effective user-id rather than real user-id.
(This option has no effect unless the process is running
as root, in which case it means not to shed all
privileges, retaining the option to regain privileges
in cases such as spawning processes. Use with caution.) | switchUID | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def untilConcludes(f, *a, **kw):
"""
Call C{f} with the given arguments, handling C{EINTR} by retrying.
@param f: A function to call.
@param *a: Positional arguments to pass to C{f}.
@param **kw: Keyword arguments to pass to C{f}.
@return: Whatever C{f} returns.
@raise: Whatever C{f} raises, except for C{IOError} or C{OSError} with
C{errno} set to C{EINTR}.
"""
while True:
try:
return f(*a, **kw)
except (IOError, OSError) as e:
if e.args[0] == errno.EINTR:
continue
raise | Call C{f} with the given arguments, handling C{EINTR} by retrying.
@param f: A function to call.
@param *a: Positional arguments to pass to C{f}.
@param **kw: Keyword arguments to pass to C{f}.
@return: Whatever C{f} returns.
@raise: Whatever C{f} raises, except for C{IOError} or C{OSError} with
C{errno} set to C{EINTR}. | untilConcludes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def mergeFunctionMetadata(f, g):
"""
Overwrite C{g}'s name and docstring with values from C{f}. Update
C{g}'s instance dictionary with C{f}'s.
@return: A function that has C{g}'s behavior and metadata merged from
C{f}.
"""
try:
g.__name__ = f.__name__
except TypeError:
pass
try:
g.__doc__ = f.__doc__
except (TypeError, AttributeError):
pass
try:
g.__dict__.update(f.__dict__)
except (TypeError, AttributeError):
pass
try:
g.__module__ = f.__module__
except TypeError:
pass
return g | Overwrite C{g}'s name and docstring with values from C{f}. Update
C{g}'s instance dictionary with C{f}'s.
@return: A function that has C{g}'s behavior and metadata merged from
C{f}. | mergeFunctionMetadata | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def nameToLabel(mname):
"""
Convert a string like a variable name into a slightly more human-friendly
string with spaces and capitalized letters.
@type mname: C{str}
@param mname: The name to convert to a label. This must be a string
which could be used as a Python identifier. Strings which do not take
this form will result in unpredictable behavior.
@rtype: C{str}
"""
labelList = []
word = ''
lastWasUpper = False
for letter in mname:
if letter.isupper() == lastWasUpper:
# Continuing a word.
word += letter
else:
# breaking a word OR beginning a word
if lastWasUpper:
# could be either
if len(word) == 1:
# keep going
word += letter
else:
# acronym
# we're processing the lowercase letter after the acronym-then-capital
lastWord = word[:-1]
firstLetter = word[-1]
labelList.append(lastWord)
word = firstLetter + letter
else:
# definitely breaking: lower to upper
labelList.append(word)
word = letter
lastWasUpper = letter.isupper()
if labelList:
labelList[0] = labelList[0].capitalize()
else:
return mname.capitalize()
labelList.append(word)
return ' '.join(labelList) | Convert a string like a variable name into a slightly more human-friendly
string with spaces and capitalized letters.
@type mname: C{str}
@param mname: The name to convert to a label. This must be a string
which could be used as a Python identifier. Strings which do not take
this form will result in unpredictable behavior.
@rtype: C{str} | nameToLabel | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def uidFromString(uidString):
"""
Convert a user identifier, as a string, into an integer UID.
@type uid: C{str}
@param uid: A string giving the base-ten representation of a UID or the
name of a user which can be converted to a UID via L{pwd.getpwnam}.
@rtype: C{int}
@return: The integer UID corresponding to the given string.
@raise ValueError: If the user name is supplied and L{pwd} is not
available.
"""
try:
return int(uidString)
except ValueError:
if pwd is None:
raise
return pwd.getpwnam(uidString)[2] | Convert a user identifier, as a string, into an integer UID.
@type uid: C{str}
@param uid: A string giving the base-ten representation of a UID or the
name of a user which can be converted to a UID via L{pwd.getpwnam}.
@rtype: C{int}
@return: The integer UID corresponding to the given string.
@raise ValueError: If the user name is supplied and L{pwd} is not
available. | uidFromString | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def gidFromString(gidString):
"""
Convert a group identifier, as a string, into an integer GID.
@type uid: C{str}
@param uid: A string giving the base-ten representation of a GID or the
name of a group which can be converted to a GID via L{grp.getgrnam}.
@rtype: C{int}
@return: The integer GID corresponding to the given string.
@raise ValueError: If the group name is supplied and L{grp} is not
available.
"""
try:
return int(gidString)
except ValueError:
if grp is None:
raise
return grp.getgrnam(gidString)[2] | Convert a group identifier, as a string, into an integer GID.
@type uid: C{str}
@param uid: A string giving the base-ten representation of a GID or the
name of a group which can be converted to a GID via L{grp.getgrnam}.
@rtype: C{int}
@return: The integer GID corresponding to the given string.
@raise ValueError: If the group name is supplied and L{grp} is not
available. | gidFromString | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def runAsEffectiveUser(euid, egid, function, *args, **kwargs):
"""
Run the given function wrapped with seteuid/setegid calls.
This will try to minimize the number of seteuid/setegid calls, comparing
current and wanted permissions
@param euid: effective UID used to call the function.
@type euid: C{int}
@type egid: effective GID used to call the function.
@param egid: C{int}
@param function: the function run with the specific permission.
@type function: any callable
@param *args: arguments passed to C{function}
@param **kwargs: keyword arguments passed to C{function}
"""
uid, gid = os.geteuid(), os.getegid()
if uid == euid and gid == egid:
return function(*args, **kwargs)
else:
if uid != 0 and (uid != euid or gid != egid):
os.seteuid(0)
if gid != egid:
os.setegid(egid)
if euid != 0 and (euid != uid or gid != egid):
os.seteuid(euid)
try:
return function(*args, **kwargs)
finally:
if euid != 0 and (uid != euid or gid != egid):
os.seteuid(0)
if gid != egid:
os.setegid(gid)
if uid != 0 and (uid != euid or gid != egid):
os.seteuid(uid) | Run the given function wrapped with seteuid/setegid calls.
This will try to minimize the number of seteuid/setegid calls, comparing
current and wanted permissions
@param euid: effective UID used to call the function.
@type euid: C{int}
@type egid: effective GID used to call the function.
@param egid: C{int}
@param function: the function run with the specific permission.
@type function: any callable
@param *args: arguments passed to C{function}
@param **kwargs: keyword arguments passed to C{function} | runAsEffectiveUser | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def runWithWarningsSuppressed(suppressedWarnings, f, *args, **kwargs):
"""
Run C{f(*args, **kwargs)}, but with some warnings suppressed.
Unlike L{twisted.internet.utils.runWithWarningsSuppressed}, it has no
special support for L{twisted.internet.defer.Deferred}.
@param suppressedWarnings: A list of arguments to pass to filterwarnings.
Must be a sequence of 2-tuples (args, kwargs).
@param f: A callable.
@param args: Arguments for C{f}.
@param kwargs: Keyword arguments for C{f}
@return: The result of C{f(*args, **kwargs)}.
"""
with warnings.catch_warnings():
for a, kw in suppressedWarnings:
warnings.filterwarnings(*a, **kw)
return f(*args, **kwargs) | Run C{f(*args, **kwargs)}, but with some warnings suppressed.
Unlike L{twisted.internet.utils.runWithWarningsSuppressed}, it has no
special support for L{twisted.internet.defer.Deferred}.
@param suppressedWarnings: A list of arguments to pass to filterwarnings.
Must be a sequence of 2-tuples (args, kwargs).
@param f: A callable.
@param args: Arguments for C{f}.
@param kwargs: Keyword arguments for C{f}
@return: The result of C{f(*args, **kwargs)}. | runWithWarningsSuppressed | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py | MIT |
def registerAdapter(adapterFactory, origInterface, *interfaceClasses):
"""Register an adapter class.
An adapter class is expected to implement the given interface, by
adapting instances implementing 'origInterface'. An adapter class's
__init__ method should accept one parameter, an instance implementing
'origInterface'.
"""
self = globalRegistry
assert interfaceClasses, "You need to pass an Interface"
global ALLOW_DUPLICATES
# deal with class->interface adapters:
if not isinstance(origInterface, interface.InterfaceClass):
origInterface = declarations.implementedBy(origInterface)
for interfaceClass in interfaceClasses:
factory = self.registered([origInterface], interfaceClass)
if factory is not None and not ALLOW_DUPLICATES:
raise ValueError("an adapter (%s) was already registered." % (factory, ))
for interfaceClass in interfaceClasses:
self.register([origInterface], interfaceClass, '', adapterFactory) | Register an adapter class.
An adapter class is expected to implement the given interface, by
adapting instances implementing 'origInterface'. An adapter class's
__init__ method should accept one parameter, an instance implementing
'origInterface'. | registerAdapter | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | MIT |
def getAdapterFactory(fromInterface, toInterface, default):
"""Return registered adapter for a given class and interface.
Note that is tied to the *Twisted* global registry, and will
thus not find adapters registered elsewhere.
"""
self = globalRegistry
if not isinstance(fromInterface, interface.InterfaceClass):
fromInterface = declarations.implementedBy(fromInterface)
factory = self.lookup1(fromInterface, toInterface)
if factory is None:
factory = default
return factory | Return registered adapter for a given class and interface.
Note that is tied to the *Twisted* global registry, and will
thus not find adapters registered elsewhere. | getAdapterFactory | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | MIT |
def _addHook(registry):
"""
Add an adapter hook which will attempt to look up adapters in the given
registry.
@type registry: L{zope.interface.adapter.AdapterRegistry}
@return: The hook which was added, for later use with L{_removeHook}.
"""
lookup = registry.lookup1
def _hook(iface, ob):
factory = lookup(declarations.providedBy(ob), iface)
if factory is None:
return None
else:
return factory(ob)
interface.adapter_hooks.append(_hook)
return _hook | Add an adapter hook which will attempt to look up adapters in the given
registry.
@type registry: L{zope.interface.adapter.AdapterRegistry}
@return: The hook which was added, for later use with L{_removeHook}. | _addHook | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | MIT |
def _removeHook(hook):
"""
Remove a previously added adapter hook.
@param hook: An object previously returned by a call to L{_addHook}. This
will be removed from the list of adapter hooks.
"""
interface.adapter_hooks.remove(hook) | Remove a previously added adapter hook.
@param hook: An object previously returned by a call to L{_addHook}. This
will be removed from the list of adapter hooks. | _removeHook | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | MIT |
def getRegistry():
"""Returns the Twisted global
C{zope.interface.adapter.AdapterRegistry} instance.
"""
return globalRegistry | Returns the Twisted global
C{zope.interface.adapter.AdapterRegistry} instance. | getRegistry | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | MIT |
def __init__(self, original):
"""Set my 'original' attribute to be the object I am adapting.
"""
self.original = original | Set my 'original' attribute to be the object I am adapting. | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | MIT |
def __conform__(self, interface):
"""
I forward __conform__ to self.original if it has it, otherwise I
simply return None.
"""
if hasattr(self.original, "__conform__"):
return self.original.__conform__(interface)
return None | I forward __conform__ to self.original if it has it, otherwise I
simply return None. | __conform__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | MIT |
def isuper(self, iface, adapter):
"""
Forward isuper to self.original
"""
return self.original.isuper(iface, adapter) | Forward isuper to self.original | isuper | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | MIT |
def setAdapter(self, interfaceClass, adapterClass):
"""
Cache a provider for the given interface, by adapting C{self} using
the given adapter class.
"""
self.setComponent(interfaceClass, adapterClass(self)) | Cache a provider for the given interface, by adapting C{self} using
the given adapter class. | setAdapter | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | MIT |
def addAdapter(self, adapterClass, ignoreClass=0):
"""Utility method that calls addComponent. I take an adapter class and
instantiate it with myself as the first argument.
@return: The adapter instantiated.
"""
adapt = adapterClass(self)
self.addComponent(adapt, ignoreClass)
return adapt | Utility method that calls addComponent. I take an adapter class and
instantiate it with myself as the first argument.
@return: The adapter instantiated. | addAdapter | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | MIT |
def setComponent(self, interfaceClass, component):
"""
Cache a provider of the given interface.
"""
self._adapterCache[reflect.qual(interfaceClass)] = component | Cache a provider of the given interface. | setComponent | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/components.py | MIT |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.