code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
182
| url
stringlengths 46
251
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def rebuild(module, doLog=1):
"""
Reload a module and do as much as possible to replace its references.
"""
global lastRebuild
lastRebuild = time.time()
if hasattr(module, 'ALLOW_TWISTED_REBUILD'):
# Is this module allowed to be rebuilt?
if not module.ALLOW_TWISTED_REBUILD:
raise RuntimeError("I am not allowed to be rebuilt.")
if doLog:
log.msg('Rebuilding {}...'.format(str(module.__name__)))
# Safely handle adapter re-registration
from twisted.python import components
components.ALLOW_DUPLICATES = True
d = module.__dict__
_modDictIDMap[id(d)] = module
newclasses = {}
classes = {}
functions = {}
values = {}
if doLog:
log.msg(' (scanning {}): '.format(str(module.__name__)))
for k, v in d.items():
if _isClassType(type(v)):
# ClassType exists on Python 2.x and earlier.
# Failure condition -- instances of classes with buggy
# __hash__/__cmp__ methods referenced at the module level...
if v.__module__ == module.__name__:
classes[v] = 1
if doLog:
log.logfile.write("c")
log.logfile.flush()
elif type(v) == types.FunctionType:
if v.__globals__ is module.__dict__:
functions[v] = 1
if doLog:
log.logfile.write("f")
log.logfile.flush()
elif isinstance(v, type):
if v.__module__ == module.__name__:
newclasses[v] = 1
if doLog:
log.logfile.write("o")
log.logfile.flush()
values.update(classes)
values.update(functions)
fromOldModule = values.__contains__
newclasses = newclasses.keys()
classes = classes.keys()
functions = functions.keys()
if doLog:
log.msg('')
log.msg(' (reload {})'.format(str(module.__name__)))
# Boom.
reload(module)
# Make sure that my traceback printing will at least be recent...
linecache.clearcache()
if doLog:
log.msg(' (cleaning {}): '.format(str(module.__name__)))
for clazz in classes:
if getattr(module, clazz.__name__) is clazz:
log.msg("WARNING: class {} not replaced by reload!".format(
reflect.qual(clazz)))
else:
if doLog:
log.logfile.write("x")
log.logfile.flush()
clazz.__bases__ = ()
clazz.__dict__.clear()
clazz.__getattr__ = __injectedgetattr__
clazz.__module__ = module.__name__
if newclasses:
import gc
for nclass in newclasses:
ga = getattr(module, nclass.__name__)
if ga is nclass:
log.msg("WARNING: new-class {} not replaced by reload!".format(
reflect.qual(nclass)))
else:
for r in gc.get_referrers(nclass):
if getattr(r, '__class__', None) is nclass:
r.__class__ = ga
if doLog:
log.msg('')
log.msg(' (fixing {}): '.format(str(module.__name__)))
modcount = 0
for mk, mod in sys.modules.items():
modcount = modcount + 1
if mod == module or mod is None:
continue
if not hasattr(mod, '__file__'):
# It's a builtin module; nothing to replace here.
continue
if hasattr(mod, '__bundle__'):
# PyObjC has a few buggy objects which segfault if you hash() them.
# It doesn't make sense to try rebuilding extension modules like
# this anyway, so don't try.
continue
changed = 0
for k, v in mod.__dict__.items():
try:
hash(v)
except Exception:
continue
if fromOldModule(v):
if _isClassType(type(v)):
if doLog:
log.logfile.write("c")
log.logfile.flush()
nv = latestClass(v)
else:
if doLog:
log.logfile.write("f")
log.logfile.flush()
nv = latestFunction(v)
changed = 1
setattr(mod, k, nv)
else:
# Replace bases of non-module classes just to be sure.
if _isClassType(type(v)):
for base in v.__bases__:
if fromOldModule(base):
latestClass(v)
if doLog and not changed and ((modcount % 10) == 0) :
log.logfile.write(".")
log.logfile.flush()
components.ALLOW_DUPLICATES = False
if doLog:
log.msg('')
log.msg(' Rebuilt {}.'.format(str(module.__name__)))
return module | Reload a module and do as much as possible to replace its references. | rebuild | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/rebuild.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/rebuild.py | MIT |
def synchronize(*klasses):
"""
Make all methods listed in each class' synchronized attribute synchronized.
The synchronized attribute should be a list of strings, consisting of the
names of methods that must be synchronized. If we are running in threaded
mode these methods will be wrapped with a lock.
"""
if threadingmodule is not None:
for klass in klasses:
for methodName in klass.synchronized:
sync = _sync(klass, klass.__dict__[methodName])
setattr(klass, methodName, sync) | Make all methods listed in each class' synchronized attribute synchronized.
The synchronized attribute should be a list of strings, consisting of the
names of methods that must be synchronized. If we are running in threaded
mode these methods will be wrapped with a lock. | synchronize | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadable.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadable.py | MIT |
def init(with_threads=1):
"""Initialize threading.
Don't bother calling this. If it needs to happen, it will happen.
"""
global threaded, _synchLockCreator, XLock
if with_threads:
if not threaded:
if threadingmodule is not None:
threaded = True
class XLock(threadingmodule._RLock, object):
def __reduce__(self):
return (unpickle_lock, ())
_synchLockCreator = XLock()
else:
raise RuntimeError("Cannot initialize threading, platform lacks thread support")
else:
if threaded:
raise RuntimeError("Cannot uninitialize threads")
else:
pass | Initialize threading.
Don't bother calling this. If it needs to happen, it will happen. | init | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadable.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadable.py | MIT |
def isInIOThread():
"""Are we in the thread responsible for I/O requests (the event loop)?
"""
return ioThread == getThreadID() | Are we in the thread responsible for I/O requests (the event loop)? | isInIOThread | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadable.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadable.py | MIT |
def registerAsIOThread():
"""Mark the current thread as responsible for I/O requests.
"""
global ioThread
ioThread = getThreadID() | Mark the current thread as responsible for I/O requests. | registerAsIOThread | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadable.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadable.py | MIT |
def __init__(self, archive, pathInArchive):
"""
Don't construct me directly. Use C{ZipArchive.child()}.
@param archive: a L{ZipArchive} instance.
@param pathInArchive: a ZIP_PATH_SEP-separated string.
"""
self.archive = archive
self.pathInArchive = pathInArchive
# self.path pretends to be os-specific because that's the way the
# 'zipimport' module does it.
sep = _coerceToFilesystemEncoding(pathInArchive, ZIP_PATH_SEP)
archiveFilename = _coerceToFilesystemEncoding(
pathInArchive, archive.zipfile.filename)
self.path = os.path.join(archiveFilename,
*(self.pathInArchive.split(sep))) | Don't construct me directly. Use C{ZipArchive.child()}.
@param archive: a L{ZipArchive} instance.
@param pathInArchive: a ZIP_PATH_SEP-separated string. | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | MIT |
def sep(self):
"""
Return a zip directory separator.
@return: The zip directory separator.
@returntype: The same type as C{self.path}.
"""
return _coerceToFilesystemEncoding(self.path, ZIP_PATH_SEP) | Return a zip directory separator.
@return: The zip directory separator.
@returntype: The same type as C{self.path}. | sep | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | MIT |
def child(self, path):
"""
Return a new ZipPath representing a path in C{self.archive} which is
a child of this path.
@note: Requesting the C{".."} (or other special name) child will not
cause L{InsecurePath} to be raised since these names do not have
any special meaning inside a zip archive. Be particularly
careful with the C{path} attribute (if you absolutely must use
it) as this means it may include special names with special
meaning outside of the context of a zip archive.
"""
joiner = _coerceToFilesystemEncoding(path, ZIP_PATH_SEP)
pathInArchive = _coerceToFilesystemEncoding(path, self.pathInArchive)
return ZipPath(self.archive, joiner.join([pathInArchive, path])) | Return a new ZipPath representing a path in C{self.archive} which is
a child of this path.
@note: Requesting the C{".."} (or other special name) child will not
cause L{InsecurePath} to be raised since these names do not have
any special meaning inside a zip archive. Be particularly
careful with the C{path} attribute (if you absolutely must use
it) as this means it may include special names with special
meaning outside of the context of a zip archive. | child | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | MIT |
def splitext(self):
"""
Return a value similar to that returned by C{os.path.splitext}.
"""
# This happens to work out because of the fact that we use OS-specific
# path separators in the constructor to construct our fake 'path'
# attribute.
return os.path.splitext(self.path) | Return a value similar to that returned by C{os.path.splitext}. | splitext | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | MIT |
def getsize(self):
"""
Retrieve this file's size.
@return: file size, in bytes
"""
pathInArchive = _coerceToFilesystemEncoding("", self.pathInArchive)
return self.archive.zipfile.NameToInfo[pathInArchive].file_size | Retrieve this file's size.
@return: file size, in bytes | getsize | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | MIT |
def getAccessTime(self):
"""
Retrieve this file's last access-time. This is the same as the last access
time for the archive.
@return: a number of seconds since the epoch
"""
return self.archive.getAccessTime() | Retrieve this file's last access-time. This is the same as the last access
time for the archive.
@return: a number of seconds since the epoch | getAccessTime | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | MIT |
def getModificationTime(self):
"""
Retrieve this file's last modification time. This is the time of
modification recorded in the zipfile.
@return: a number of seconds since the epoch.
"""
pathInArchive = _coerceToFilesystemEncoding("", self.pathInArchive)
return time.mktime(
self.archive.zipfile.NameToInfo[pathInArchive].date_time
+ (0, 0, 0)) | Retrieve this file's last modification time. This is the time of
modification recorded in the zipfile.
@return: a number of seconds since the epoch. | getModificationTime | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | MIT |
def getStatusChangeTime(self):
"""
Retrieve this file's last modification time. This name is provided for
compatibility, and returns the same value as getmtime.
@return: a number of seconds since the epoch.
"""
return self.getModificationTime() | Retrieve this file's last modification time. This name is provided for
compatibility, and returns the same value as getmtime.
@return: a number of seconds since the epoch. | getStatusChangeTime | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | MIT |
def __init__(self, archivePathname):
"""
Create a ZipArchive, treating the archive at archivePathname as a zip
file.
@param archivePathname: a L{bytes} or L{unicode}, naming a path in the
filesystem.
"""
self.path = archivePathname
self.zipfile = ZipFile(_coerceToFilesystemEncoding('',
archivePathname))
self.pathInArchive = _coerceToFilesystemEncoding(archivePathname, '')
# zipfile is already wasting O(N) memory on cached ZipInfo instances,
# so there's no sense in trying to do this lazily or intelligently
self.childmap = {} # map parent: list of children
for name in self.zipfile.namelist():
name = _coerceToFilesystemEncoding(self.path, name).split(self.sep)
for x in range(len(name)):
child = name[-x]
parent = self.sep.join(name[:-x])
if parent not in self.childmap:
self.childmap[parent] = {}
self.childmap[parent][child] = 1
parent = _coerceToFilesystemEncoding(archivePathname, '') | Create a ZipArchive, treating the archive at archivePathname as a zip
file.
@param archivePathname: a L{bytes} or L{unicode}, naming a path in the
filesystem. | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | MIT |
def child(self, path):
"""
Create a ZipPath pointing at a path within the archive.
@param path: a L{bytes} or L{unicode} with no path separators in it
(either '/' or the system path separator, if it's different).
"""
return ZipPath(self, path) | Create a ZipPath pointing at a path within the archive.
@param path: a L{bytes} or L{unicode} with no path separators in it
(either '/' or the system path separator, if it's different). | child | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | MIT |
def exists(self):
"""
Returns C{True} if the underlying archive exists.
"""
return FilePath(self.zipfile.filename).exists() | Returns C{True} if the underlying archive exists. | exists | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | MIT |
def getAccessTime(self):
"""
Return the archive file's last access time.
"""
return FilePath(self.zipfile.filename).getAccessTime() | Return the archive file's last access time. | getAccessTime | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | MIT |
def getModificationTime(self):
"""
Return the archive file's modification time.
"""
return FilePath(self.zipfile.filename).getModificationTime() | Return the archive file's modification time. | getModificationTime | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | MIT |
def getStatusChangeTime(self):
"""
Return the archive file's status change time.
"""
return FilePath(self.zipfile.filename).getStatusChangeTime() | Return the archive file's status change time. | getStatusChangeTime | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zippath.py | MIT |
def getDataDirectory(moduleName=None):
"""
Get a data directory for the caller function, or C{moduleName} if given.
@param moduleName: The module name if you don't wish to have the caller's
module.
@type moduleName: L{str}
@returns: A directory for putting data in.
@rtype: L{str}
"""
if not moduleName:
caller = currentframe(1)
moduleName = inspect.getmodule(caller).__name__
return appdirs.user_data_dir(moduleName) | Get a data directory for the caller function, or C{moduleName} if given.
@param moduleName: The module name if you don't wish to have the caller's
module.
@type moduleName: L{str}
@returns: A directory for putting data in.
@rtype: L{str} | getDataDirectory | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_appdirs.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_appdirs.py | MIT |
def shortPythonVersion():
"""
Returns the Python version as a dot-separated string.
"""
return "%s.%s.%s" % sys.version_info[:3] | Returns the Python version as a dot-separated string. | shortPythonVersion | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | MIT |
def isKnown(self):
"""
Do we know about this platform?
@return: Boolean indicating whether this is a known platform or not.
@rtype: C{bool}
"""
return self.type != None | Do we know about this platform?
@return: Boolean indicating whether this is a known platform or not.
@rtype: C{bool} | isKnown | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | MIT |
def getType(self):
"""
Get platform type.
@return: Either 'posix', 'win32' or 'java'
@rtype: C{str}
"""
return self.type | Get platform type.
@return: Either 'posix', 'win32' or 'java'
@rtype: C{str} | getType | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | MIT |
def isMacOSX(self):
"""
Check if current platform is macOS.
@return: C{True} if the current platform has been detected as macOS.
@rtype: C{bool}
"""
return self._platform == "darwin" | Check if current platform is macOS.
@return: C{True} if the current platform has been detected as macOS.
@rtype: C{bool} | isMacOSX | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | MIT |
def isWinNT(self):
"""
Are we running in Windows NT?
This is deprecated and always returns C{True} on win32 because
Twisted only supports Windows NT-derived platforms at this point.
@return: C{True} if the current platform has been detected as
Windows NT.
@rtype: C{bool}
"""
warnings.warn(
"twisted.python.runtime.Platform.isWinNT was deprecated in "
"Twisted 13.0. Use Platform.isWindows instead.",
DeprecationWarning, stacklevel=2)
return self.isWindows() | Are we running in Windows NT?
This is deprecated and always returns C{True} on win32 because
Twisted only supports Windows NT-derived platforms at this point.
@return: C{True} if the current platform has been detected as
Windows NT.
@rtype: C{bool} | isWinNT | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | MIT |
def isWindows(self):
"""
Are we running in Windows?
@return: C{True} if the current platform has been detected as
Windows.
@rtype: C{bool}
"""
return self.getType() == 'win32' | Are we running in Windows?
@return: C{True} if the current platform has been detected as
Windows.
@rtype: C{bool} | isWindows | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | MIT |
def isVista(self):
"""
Check if current platform is Windows Vista or Windows Server 2008.
@return: C{True} if the current platform has been detected as Vista
@rtype: C{bool}
"""
if getattr(sys, "getwindowsversion", None) is not None:
return sys.getwindowsversion()[0] == 6
else:
return False | Check if current platform is Windows Vista or Windows Server 2008.
@return: C{True} if the current platform has been detected as Vista
@rtype: C{bool} | isVista | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | MIT |
def isLinux(self):
"""
Check if current platform is Linux.
@return: C{True} if the current platform has been detected as Linux.
@rtype: C{bool}
"""
return self._platform.startswith("linux") | Check if current platform is Linux.
@return: C{True} if the current platform has been detected as Linux.
@rtype: C{bool} | isLinux | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | MIT |
def isDocker(self, _initCGroupLocation="/proc/1/cgroup"):
"""
Check if the current platform is Linux in a Docker container.
@return: C{True} if the current platform has been detected as Linux
inside a Docker container.
@rtype: C{bool}
"""
if not self.isLinux():
return False
from twisted.python.filepath import FilePath
# Ask for the cgroups of init (pid 1)
initCGroups = FilePath(_initCGroupLocation)
if initCGroups.exists():
# The cgroups file looks like "2:cpu:/". The third element will
# begin with /docker if it is inside a Docker container.
controlGroups = [x.split(b":")
for x in initCGroups.getContent().split(b"\n")]
for group in controlGroups:
if len(group) == 3 and group[2].startswith(b"/docker/"):
# If it starts with /docker/, we're in a docker container
return True
return False | Check if the current platform is Linux in a Docker container.
@return: C{True} if the current platform has been detected as Linux
inside a Docker container.
@rtype: C{bool} | isDocker | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | MIT |
def _supportsSymlinks(self):
"""
Check for symlink support usable for Twisted's purposes.
@return: C{True} if symlinks are supported on the current platform,
otherwise C{False}.
@rtype: L{bool}
"""
if self.isWindows():
# We do the isWindows() check as newer Pythons support the symlink
# support in Vista+, but only if you have some obscure permission
# (SeCreateSymbolicLinkPrivilege), which can only be given on
# platforms with msc.exe (so, Business/Enterprise editions).
# This uncommon requirement makes the Twisted test suite test fail
# in 99.99% of cases as general users don't have permission to do
# it, even if there is "symlink support".
return False
else:
# If we're not on Windows, check for existence of os.symlink.
try:
os.symlink
except AttributeError:
return False
else:
return True | Check for symlink support usable for Twisted's purposes.
@return: C{True} if symlinks are supported on the current platform,
otherwise C{False}.
@rtype: L{bool} | _supportsSymlinks | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | MIT |
def supportsThreads(self):
"""
Can threads be created?
@return: C{True} if the threads are supported on the current platform.
@rtype: C{bool}
"""
try:
import threading
return threading is not None # shh pyflakes
except ImportError:
return False | Can threads be created?
@return: C{True} if the threads are supported on the current platform.
@rtype: C{bool} | supportsThreads | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | MIT |
def supportsINotify(self):
"""
Return C{True} if we can use the inotify API on this platform.
@since: 10.1
"""
try:
from twisted.python._inotify import INotifyError, init
except ImportError:
return False
try:
os.close(init())
except INotifyError:
return False
return True | Return C{True} if we can use the inotify API on this platform.
@since: 10.1 | supportsINotify | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/runtime.py | MIT |
def __init__(self, writer):
"""
@param writer: A file-like object, opened in bytes mode.
"""
self.writer = writer | @param writer: A file-like object, opened in bytes mode. | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/htmlizer.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/htmlizer.py | MIT |
def init():
"""
Create an inotify instance and return the associated file descriptor.
"""
fd = libc.inotify_init()
if fd < 0:
raise INotifyError("INotify initialization error.")
return fd | Create an inotify instance and return the associated file descriptor. | init | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_inotify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_inotify.py | MIT |
def add(fd, path, mask):
"""
Add a watch for the given path to the inotify file descriptor, and return
the watch descriptor.
@param fd: The file descriptor returned by C{libc.inotify_init}.
@type fd: L{int}
@param path: The path to watch via inotify.
@type path: L{twisted.python.filepath.FilePath}
@param mask: Bitmask specifying the events that inotify should monitor.
@type mask: L{int}
"""
wd = libc.inotify_add_watch(fd, path.asBytesMode().path, mask)
if wd < 0:
raise INotifyError("Failed to add watch on '%r' - (%r)" % (path, wd))
return wd | Add a watch for the given path to the inotify file descriptor, and return
the watch descriptor.
@param fd: The file descriptor returned by C{libc.inotify_init}.
@type fd: L{int}
@param path: The path to watch via inotify.
@type path: L{twisted.python.filepath.FilePath}
@param mask: Bitmask specifying the events that inotify should monitor.
@type mask: L{int} | add | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_inotify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_inotify.py | MIT |
def remove(fd, wd):
"""
Remove the given watch descriptor from the inotify file descriptor.
"""
# When inotify_rm_watch returns -1 there's an error:
# The errno for this call can be either one of the following:
# EBADF: fd is not a valid file descriptor.
# EINVAL: The watch descriptor wd is not valid; or fd is
# not an inotify file descriptor.
#
# if we can't access the errno here we cannot even raise
# an exception and we need to ignore the problem, one of
# the most common cases is when you remove a directory from
# the filesystem and that directory is observed. When inotify
# tries to call inotify_rm_watch with a non existing directory
# either of the 2 errors might come up because the files inside
# it might have events generated way before they were handled.
# Unfortunately only ctypes in Python 2.6 supports accessing errno:
# http://bugs.python.org/issue1798 and in order to solve
# the problem for previous versions we need to introduce
# code that is quite complex:
# http://stackoverflow.com/questions/661017/access-to-errno-from-python
#
# See #4310 for future resolution of this issue.
libc.inotify_rm_watch(fd, wd) | Remove the given watch descriptor from the inotify file descriptor. | remove | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_inotify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_inotify.py | MIT |
def initializeModule(libc):
"""
Initialize the module, checking if the expected APIs exist and setting the
argtypes and restype for C{inotify_init}, C{inotify_add_watch}, and
C{inotify_rm_watch}.
"""
for function in ("inotify_add_watch", "inotify_init", "inotify_rm_watch"):
if getattr(libc, function, None) is None:
raise ImportError("libc6 2.4 or higher needed")
libc.inotify_init.argtypes = []
libc.inotify_init.restype = ctypes.c_int
libc.inotify_rm_watch.argtypes = [
ctypes.c_int, ctypes.c_int]
libc.inotify_rm_watch.restype = ctypes.c_int
libc.inotify_add_watch.argtypes = [
ctypes.c_int, ctypes.c_char_p, ctypes.c_uint32]
libc.inotify_add_watch.restype = ctypes.c_int | Initialize the module, checking if the expected APIs exist and setting the
argtypes and restype for C{inotify_init}, C{inotify_add_watch}, and
C{inotify_rm_watch}. | initializeModule | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_inotify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_inotify.py | MIT |
def __init__(self, minthreads=5, maxthreads=20, name=None):
"""
Create a new threadpool.
@param minthreads: minimum number of threads in the pool
@type minthreads: L{int}
@param maxthreads: maximum number of threads in the pool
@type maxthreads: L{int}
@param name: The name to give this threadpool; visible in log messages.
@type name: native L{str}
"""
assert minthreads >= 0, 'minimum is negative'
assert minthreads <= maxthreads, 'minimum is greater than maximum'
self.min = minthreads
self.max = maxthreads
self.name = name
self.threads = []
def trackingThreadFactory(*a, **kw):
thread = self.threadFactory(*a, name=self._generateName(), **kw)
self.threads.append(thread)
return thread
def currentLimit():
if not self.started:
return 0
return self.max
self._team = self._pool(currentLimit, trackingThreadFactory) | Create a new threadpool.
@param minthreads: minimum number of threads in the pool
@type minthreads: L{int}
@param maxthreads: maximum number of threads in the pool
@type maxthreads: L{int}
@param name: The name to give this threadpool; visible in log messages.
@type name: native L{str} | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | MIT |
def workers(self):
"""
For legacy compatibility purposes, return a total number of workers.
@return: the current number of workers, both idle and busy (but not
those that have been quit by L{ThreadPool.adjustPoolsize})
@rtype: L{int}
"""
stats = self._team.statistics()
return stats.idleWorkerCount + stats.busyWorkerCount | For legacy compatibility purposes, return a total number of workers.
@return: the current number of workers, both idle and busy (but not
those that have been quit by L{ThreadPool.adjustPoolsize})
@rtype: L{int} | workers | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | MIT |
def working(self):
"""
For legacy compatibility purposes, return the number of busy workers as
expressed by a list the length of that number.
@return: the number of workers currently processing a work item.
@rtype: L{list} of L{None}
"""
return [None] * self._team.statistics().busyWorkerCount | For legacy compatibility purposes, return the number of busy workers as
expressed by a list the length of that number.
@return: the number of workers currently processing a work item.
@rtype: L{list} of L{None} | working | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | MIT |
def waiters(self):
"""
For legacy compatibility purposes, return the number of idle workers as
expressed by a list the length of that number.
@return: the number of workers currently alive (with an allocated
thread) but waiting for new work.
@rtype: L{list} of L{None}
"""
return [None] * self._team.statistics().idleWorkerCount | For legacy compatibility purposes, return the number of idle workers as
expressed by a list the length of that number.
@return: the number of workers currently alive (with an allocated
thread) but waiting for new work.
@rtype: L{list} of L{None} | waiters | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | MIT |
def qsize(q):
"""
Pretend to be a Python threading Queue and return the
number of as-yet-unconsumed tasks.
@return: the amount of backlogged work not yet dispatched to a
worker.
@rtype: L{int}
"""
return self._team.statistics().backloggedWorkCount | Pretend to be a Python threading Queue and return the
number of as-yet-unconsumed tasks.
@return: the amount of backlogged work not yet dispatched to a
worker.
@rtype: L{int} | _queue.qsize | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | MIT |
def _queue(self):
"""
For legacy compatibility purposes, return an object with a C{qsize}
method that indicates the amount of work not yet allocated to a worker.
@return: an object with a C{qsize} method.
"""
class NotAQueue(object):
def qsize(q):
"""
Pretend to be a Python threading Queue and return the
number of as-yet-unconsumed tasks.
@return: the amount of backlogged work not yet dispatched to a
worker.
@rtype: L{int}
"""
return self._team.statistics().backloggedWorkCount
return NotAQueue() | For legacy compatibility purposes, return an object with a C{qsize}
method that indicates the amount of work not yet allocated to a worker.
@return: an object with a C{qsize} method. | _queue | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | MIT |
def start(self):
"""
Start the threadpool.
"""
self.joined = False
self.started = True
# Start some threads.
self.adjustPoolsize()
backlog = self._team.statistics().backloggedWorkCount
if backlog:
self._team.grow(backlog) | Start the threadpool. | start | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | MIT |
def startAWorker(self):
"""
Increase the number of available workers for the thread pool by 1, up
to the maximum allowed by L{ThreadPool.max}.
"""
self._team.grow(1) | Increase the number of available workers for the thread pool by 1, up
to the maximum allowed by L{ThreadPool.max}. | startAWorker | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | MIT |
def _generateName(self):
"""
Generate a name for a new pool thread.
@return: A distinctive name for the thread.
@rtype: native L{str}
"""
return "PoolThread-%s-%s" % (self.name or id(self), self.workers) | Generate a name for a new pool thread.
@return: A distinctive name for the thread.
@rtype: native L{str} | _generateName | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | MIT |
def stopAWorker(self):
"""
Decrease the number of available workers by 1, by quitting one as soon
as it's idle.
"""
self._team.shrink(1) | Decrease the number of available workers by 1, by quitting one as soon
as it's idle. | stopAWorker | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | MIT |
def callInThread(self, func, *args, **kw):
"""
Call a callable object in a separate thread.
@param func: callable object to be called in separate thread
@param args: positional arguments to be passed to C{func}
@param kw: keyword args to be passed to C{func}
"""
self.callInThreadWithCallback(None, func, *args, **kw) | Call a callable object in a separate thread.
@param func: callable object to be called in separate thread
@param args: positional arguments to be passed to C{func}
@param kw: keyword args to be passed to C{func} | callInThread | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | MIT |
def callInThreadWithCallback(self, onResult, func, *args, **kw):
"""
Call a callable object in a separate thread and call C{onResult} with
the return value, or a L{twisted.python.failure.Failure} if the
callable raises an exception.
The callable is allowed to block, but the C{onResult} function must not
block and should perform as little work as possible.
A typical action for C{onResult} for a threadpool used with a Twisted
reactor would be to schedule a L{twisted.internet.defer.Deferred} to
fire in the main reactor thread using C{.callFromThread}. Note that
C{onResult} is called inside the separate thread, not inside the
reactor thread.
@param onResult: a callable with the signature C{(success, result)}.
If the callable returns normally, C{onResult} is called with
C{(True, result)} where C{result} is the return value of the
callable. If the callable throws an exception, C{onResult} is
called with C{(False, failure)}.
Optionally, C{onResult} may be L{None}, in which case it is not
called at all.
@param func: callable object to be called in separate thread
@param args: positional arguments to be passed to C{func}
@param kw: keyword arguments to be passed to C{func}
"""
if self.joined:
return
ctx = context.theContextTracker.currentContext().contexts[-1]
def inContext():
try:
result = inContext.theWork()
ok = True
except:
result = Failure()
ok = False
inContext.theWork = None
if inContext.onResult is not None:
inContext.onResult(ok, result)
inContext.onResult = None
elif not ok:
log.err(result)
# Avoid closing over func, ctx, args, kw so that we can carefully
# manage their lifecycle. See
# test_threadCreationArgumentsCallInThreadWithCallback.
inContext.theWork = lambda: context.call(ctx, func, *args, **kw)
inContext.onResult = onResult
self._team.do(inContext) | Call a callable object in a separate thread and call C{onResult} with
the return value, or a L{twisted.python.failure.Failure} if the
callable raises an exception.
The callable is allowed to block, but the C{onResult} function must not
block and should perform as little work as possible.
A typical action for C{onResult} for a threadpool used with a Twisted
reactor would be to schedule a L{twisted.internet.defer.Deferred} to
fire in the main reactor thread using C{.callFromThread}. Note that
C{onResult} is called inside the separate thread, not inside the
reactor thread.
@param onResult: a callable with the signature C{(success, result)}.
If the callable returns normally, C{onResult} is called with
C{(True, result)} where C{result} is the return value of the
callable. If the callable throws an exception, C{onResult} is
called with C{(False, failure)}.
Optionally, C{onResult} may be L{None}, in which case it is not
called at all.
@param func: callable object to be called in separate thread
@param args: positional arguments to be passed to C{func}
@param kw: keyword arguments to be passed to C{func} | callInThreadWithCallback | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | MIT |
def stop(self):
"""
Shutdown the threads in the threadpool.
"""
self.joined = True
self.started = False
self._team.quit()
for thread in self.threads:
thread.join() | Shutdown the threads in the threadpool. | stop | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | MIT |
def adjustPoolsize(self, minthreads=None, maxthreads=None):
"""
Adjust the number of available threads by setting C{min} and C{max} to
new values.
@param minthreads: The new value for L{ThreadPool.min}.
@param maxthreads: The new value for L{ThreadPool.max}.
"""
if minthreads is None:
minthreads = self.min
if maxthreads is None:
maxthreads = self.max
assert minthreads >= 0, 'minimum is negative'
assert minthreads <= maxthreads, 'minimum is greater than maximum'
self.min = minthreads
self.max = maxthreads
if not self.started:
return
# Kill of some threads if we have too many.
if self.workers > self.max:
self._team.shrink(self.workers - self.max)
# Start some threads if we have too few.
if self.workers < self.min:
self._team.grow(self.min - self.workers) | Adjust the number of available threads by setting C{min} and C{max} to
new values.
@param minthreads: The new value for L{ThreadPool.min}.
@param maxthreads: The new value for L{ThreadPool.max}. | adjustPoolsize | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | MIT |
def dumpStats(self):
"""
Dump some plain-text informational messages to the log about the state
of this L{ThreadPool}.
"""
log.msg('waiters: %s' % (self.waiters,))
log.msg('workers: %s' % (self.working,))
log.msg('total: %s' % (self.threads,)) | Dump some plain-text informational messages to the log about the state
of this L{ThreadPool}. | dumpStats | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/threadpool.py | MIT |
def _rereconstituter(name):
"""
Attriute declaration to preserve mutability on L{URLPath}.
@param name: a public attribute name
@type name: native L{str}
@return: a descriptor which retrieves the private version of the attribute
on get and calls rerealize on set.
"""
privateName = nativeString("_") + name
return property(
lambda self: getattr(self, privateName),
lambda self, value: (setattr(self, privateName,
value if isinstance(value, bytes)
else value.encode("charmap")) or
self._reconstitute())
) | Attriute declaration to preserve mutability on L{URLPath}.
@param name: a public attribute name
@type name: native L{str}
@return: a descriptor which retrieves the private version of the attribute
on get and calls rerealize on set. | _rereconstituter | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | MIT |
def _reconstitute(self):
"""
Reconstitute this L{URLPath} from all its given attributes.
"""
urltext = urlquote(
urlparse.urlunsplit((self._scheme, self._netloc,
self._path, self._query, self._fragment)),
safe=_allascii
)
self._url = _URL.fromText(urltext.encode("ascii").decode("ascii")) | Reconstitute this L{URLPath} from all its given attributes. | _reconstitute | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | MIT |
def _fromURL(cls, urlInstance):
"""
Reconstruct all the public instance variables of this L{URLPath} from
its underlying L{_URL}.
@param urlInstance: the object to base this L{URLPath} on.
@type urlInstance: L{_URL}
@return: a new L{URLPath}
"""
self = cls.__new__(cls)
self._url = urlInstance.replace(path=urlInstance.path or [u""])
self._scheme = self._url.scheme.encode("ascii")
self._netloc = self._url.authority().encode("ascii")
self._path = (_URL(path=self._url.path,
rooted=True).asURI().asText()
.encode("ascii"))
self._query = (_URL(query=self._url.query).asURI().asText()
.encode("ascii"))[1:]
self._fragment = self._url.fragment.encode("ascii")
return self | Reconstruct all the public instance variables of this L{URLPath} from
its underlying L{_URL}.
@param urlInstance: the object to base this L{URLPath} on.
@type urlInstance: L{_URL}
@return: a new L{URLPath} | _fromURL | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | MIT |
def pathList(self, unquote=False, copy=True):
"""
Split this URL's path into its components.
@param unquote: whether to remove %-encoding from the returned strings.
@param copy: (ignored, do not use)
@return: The components of C{self.path}
@rtype: L{list} of L{bytes}
"""
segments = self._url.path
mapper = lambda x: x.encode("ascii")
if unquote:
mapper = (lambda x, m=mapper: m(urlunquote(x)))
return [b''] + [mapper(segment) for segment in segments] | Split this URL's path into its components.
@param unquote: whether to remove %-encoding from the returned strings.
@param copy: (ignored, do not use)
@return: The components of C{self.path}
@rtype: L{list} of L{bytes} | pathList | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | MIT |
def fromString(klass, url):
"""
Make a L{URLPath} from a L{str} or L{unicode}.
@param url: A L{str} representation of a URL.
@type url: L{str} or L{unicode}.
@return: a new L{URLPath} derived from the given string.
@rtype: L{URLPath}
"""
if not isinstance(url, (str, unicode)):
raise ValueError("'url' must be a str or unicode")
if isinstance(url, bytes):
# On Python 2, accepting 'str' (for compatibility) means we might
# get 'bytes'. On py3, this will not work with bytes due to the
# check above.
return klass.fromBytes(url)
return klass._fromURL(_URL.fromText(url)) | Make a L{URLPath} from a L{str} or L{unicode}.
@param url: A L{str} representation of a URL.
@type url: L{str} or L{unicode}.
@return: a new L{URLPath} derived from the given string.
@rtype: L{URLPath} | fromString | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | MIT |
def fromBytes(klass, url):
"""
Make a L{URLPath} from a L{bytes}.
@param url: A L{bytes} representation of a URL.
@type url: L{bytes}
@return: a new L{URLPath} derived from the given L{bytes}.
@rtype: L{URLPath}
@since: 15.4
"""
if not isinstance(url, bytes):
raise ValueError("'url' must be bytes")
quoted = urlquote(url, safe=_allascii)
if isinstance(quoted, bytes):
# This will only be bytes on python 2, where we can transform it
# into unicode. On python 3, urlquote always returns str.
quoted = quoted.decode("ascii")
return klass.fromString(quoted) | Make a L{URLPath} from a L{bytes}.
@param url: A L{bytes} representation of a URL.
@type url: L{bytes}
@return: a new L{URLPath} derived from the given L{bytes}.
@rtype: L{URLPath}
@since: 15.4 | fromBytes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | MIT |
def fromRequest(klass, request):
"""
Make a L{URLPath} from a L{twisted.web.http.Request}.
@param request: A L{twisted.web.http.Request} to make the L{URLPath}
from.
@return: a new L{URLPath} derived from the given request.
@rtype: L{URLPath}
"""
return klass.fromBytes(request.prePathURL()) | Make a L{URLPath} from a L{twisted.web.http.Request}.
@param request: A L{twisted.web.http.Request} to make the L{URLPath}
from.
@return: a new L{URLPath} derived from the given request.
@rtype: L{URLPath} | fromRequest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | MIT |
def _mod(self, newURL, keepQuery):
"""
Return a modified copy of C{self} using C{newURL}, keeping the query
string if C{keepQuery} is C{True}.
@param newURL: a L{URL} to derive a new L{URLPath} from
@type newURL: L{URL}
@param keepQuery: if C{True}, preserve the query parameters from
C{self} on the new L{URLPath}; if C{False}, give the new L{URLPath}
no query parameters.
@type keepQuery: L{bool}
@return: a new L{URLPath}
"""
return self._fromURL(newURL.replace(
fragment=u'', query=self._url.query if keepQuery else ()
)) | Return a modified copy of C{self} using C{newURL}, keeping the query
string if C{keepQuery} is C{True}.
@param newURL: a L{URL} to derive a new L{URLPath} from
@type newURL: L{URL}
@param keepQuery: if C{True}, preserve the query parameters from
C{self} on the new L{URLPath}; if C{False}, give the new L{URLPath}
no query parameters.
@type keepQuery: L{bool}
@return: a new L{URLPath} | _mod | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | MIT |
def sibling(self, path, keepQuery=False):
"""
Get the sibling of the current L{URLPath}. A sibling is a file which
is in the same directory as the current file.
@param path: The path of the sibling.
@type path: L{bytes}
@param keepQuery: Whether to keep the query parameters on the returned
L{URLPath}.
@type: keepQuery: L{bool}
@return: a new L{URLPath}
"""
return self._mod(self._url.sibling(path.decode("ascii")), keepQuery) | Get the sibling of the current L{URLPath}. A sibling is a file which
is in the same directory as the current file.
@param path: The path of the sibling.
@type path: L{bytes}
@param keepQuery: Whether to keep the query parameters on the returned
L{URLPath}.
@type: keepQuery: L{bool}
@return: a new L{URLPath} | sibling | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | MIT |
def child(self, path, keepQuery=False):
"""
Get the child of this L{URLPath}.
@param path: The path of the child.
@type path: L{bytes}
@param keepQuery: Whether to keep the query parameters on the returned
L{URLPath}.
@type: keepQuery: L{bool}
@return: a new L{URLPath}
"""
return self._mod(self._url.child(path.decode("ascii")), keepQuery) | Get the child of this L{URLPath}.
@param path: The path of the child.
@type path: L{bytes}
@param keepQuery: Whether to keep the query parameters on the returned
L{URLPath}.
@type: keepQuery: L{bool}
@return: a new L{URLPath} | child | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | MIT |
def parent(self, keepQuery=False):
"""
Get the parent directory of this L{URLPath}.
@param keepQuery: Whether to keep the query parameters on the returned
L{URLPath}.
@type: keepQuery: L{bool}
@return: a new L{URLPath}
"""
return self._mod(self._url.click(u".."), keepQuery) | Get the parent directory of this L{URLPath}.
@param keepQuery: Whether to keep the query parameters on the returned
L{URLPath}.
@type: keepQuery: L{bool}
@return: a new L{URLPath} | parent | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | MIT |
def here(self, keepQuery=False):
"""
Get the current directory of this L{URLPath}.
@param keepQuery: Whether to keep the query parameters on the returned
L{URLPath}.
@type: keepQuery: L{bool}
@return: a new L{URLPath}
"""
return self._mod(self._url.click(u"."), keepQuery) | Get the current directory of this L{URLPath}.
@param keepQuery: Whether to keep the query parameters on the returned
L{URLPath}.
@type: keepQuery: L{bool}
@return: a new L{URLPath} | here | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | MIT |
def click(self, st):
"""
Return a path which is the URL where a browser would presumably take
you if you clicked on a link with an HREF as given.
@param st: A relative URL, to be interpreted relative to C{self} as the
base URL.
@type st: L{bytes}
@return: a new L{URLPath}
"""
return self._fromURL(self._url.click(st.decode("ascii"))) | Return a path which is the URL where a browser would presumably take
you if you clicked on a link with an HREF as given.
@param st: A relative URL, to be interpreted relative to C{self} as the
base URL.
@type st: L{bytes}
@return: a new L{URLPath} | click | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | MIT |
def __str__(self):
"""
The L{str} of a L{URLPath} is its URL text.
"""
return nativeString(self._url.asURI().asText()) | The L{str} of a L{URLPath} is its URL text. | __str__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | MIT |
def __repr__(self):
"""
The L{repr} of a L{URLPath} is an eval-able expression which will
construct a similar L{URLPath}.
"""
return ('URLPath(scheme=%r, netloc=%r, path=%r, query=%r, fragment=%r)'
% (self.scheme, self.netloc, self.path, self.query,
self.fragment)) | The L{repr} of a L{URLPath} is an eval-able expression which will
construct a similar L{URLPath}. | __repr__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/urlpath.py | MIT |
def shellComplete(config, cmdName, words, shellCompFile):
"""
Perform shell completion.
A completion function (shell script) is generated for the requested
shell and written to C{shellCompFile}, typically C{stdout}. The result
is then eval'd by the shell to produce the desired completions.
@type config: L{twisted.python.usage.Options}
@param config: The L{twisted.python.usage.Options} instance to generate
completions for.
@type cmdName: C{str}
@param cmdName: The name of the command we're generating completions for.
In the case of zsh, this is used to print an appropriate
"#compdef $CMD" line at the top of the output. This is
not necessary for the functionality of the system, but it
helps in debugging, since the output we produce is properly
formed and may be saved in a file and used as a stand-alone
completion function.
@type words: C{list} of C{str}
@param words: The raw command-line words passed to use by the shell
stub function. argv[0] has already been stripped off.
@type shellCompFile: C{file}
@param shellCompFile: The file to write completion data to.
"""
# If given a file with unicode semantics, such as sys.stdout on Python 3,
# we must get at the the underlying buffer which has bytes semantics.
if shellCompFile and ioType(shellCompFile) == unicode:
shellCompFile = shellCompFile.buffer
# shellName is provided for forward-compatibility. It is not used,
# since we currently only support zsh.
shellName, position = words[-1].split(":")
position = int(position)
# zsh gives the completion position ($CURRENT) as a 1-based index,
# and argv[0] has already been stripped off, so we subtract 2 to
# get the real 0-based index.
position -= 2
cWord = words[position]
# since the user may hit TAB at any time, we may have been called with an
# incomplete command-line that would generate getopt errors if parsed
# verbatim. However, we must do *some* parsing in order to determine if
# there is a specific subcommand that we need to provide completion for.
# So, to make the command-line more sane we work backwards from the
# current completion position and strip off all words until we find one
# that "looks" like a subcommand. It may in fact be the argument to a
# normal command-line option, but that won't matter for our purposes.
while position >= 1:
if words[position - 1].startswith("-"):
position -= 1
else:
break
words = words[:position]
subCommands = getattr(config, 'subCommands', None)
if subCommands:
# OK, this command supports sub-commands, so lets see if we have been
# given one.
# If the command-line arguments are not valid then we won't be able to
# sanely detect the sub-command, so just generate completions as if no
# sub-command was found.
args = None
try:
opts, args = getopt.getopt(words,
config.shortOpt, config.longOpt)
except getopt.error:
pass
if args:
# yes, we have a subcommand. Try to find it.
for (cmd, short, parser, doc) in config.subCommands:
if args[0] == cmd or args[0] == short:
subOptions = parser()
subOptions.parent = config
gen = ZshSubcommandBuilder(subOptions, config, cmdName,
shellCompFile)
gen.write()
return
# sub-command not given, or did not match any knowns sub-command names
genSubs = True
if cWord.startswith("-"):
# optimization: if the current word being completed starts
# with a hyphen then it can't be a sub-command, so skip
# the expensive generation of the sub-command list
genSubs = False
gen = ZshBuilder(config, cmdName, shellCompFile)
gen.write(genSubs=genSubs)
else:
gen = ZshBuilder(config, cmdName, shellCompFile)
gen.write() | Perform shell completion.
A completion function (shell script) is generated for the requested
shell and written to C{shellCompFile}, typically C{stdout}. The result
is then eval'd by the shell to produce the desired completions.
@type config: L{twisted.python.usage.Options}
@param config: The L{twisted.python.usage.Options} instance to generate
completions for.
@type cmdName: C{str}
@param cmdName: The name of the command we're generating completions for.
In the case of zsh, this is used to print an appropriate
"#compdef $CMD" line at the top of the output. This is
not necessary for the functionality of the system, but it
helps in debugging, since the output we produce is properly
formed and may be saved in a file and used as a stand-alone
completion function.
@type words: C{list} of C{str}
@param words: The raw command-line words passed to use by the shell
stub function. argv[0] has already been stripped off.
@type shellCompFile: C{file}
@param shellCompFile: The file to write completion data to. | shellComplete | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | MIT |
def write(self, genSubs=True):
"""
Generate the completion function and write it to the output file
@return: L{None}
@type genSubs: C{bool}
@param genSubs: Flag indicating whether or not completions for the list
of subcommand should be generated. Only has an effect
if the C{subCommands} attribute has been defined on the
L{twisted.python.usage.Options} instance.
"""
if genSubs and getattr(self.options, 'subCommands', None) is not None:
gen = ZshArgumentsGenerator(self.options, self.cmdName, self.file)
gen.extraActions.insert(0, SubcommandAction())
gen.write()
self.file.write(b'local _zsh_subcmds_array\n_zsh_subcmds_array=(\n')
for (cmd, short, parser, desc) in self.options.subCommands:
self.file.write(
b'\"' + cmd.encode('utf-8') + b':' + desc.encode('utf-8') +b'\"\n')
self.file.write(b")\n\n")
self.file.write(b'_describe "sub-command" _zsh_subcmds_array\n')
else:
gen = ZshArgumentsGenerator(self.options, self.cmdName, self.file)
gen.write() | Generate the completion function and write it to the output file
@return: L{None}
@type genSubs: C{bool}
@param genSubs: Flag indicating whether or not completions for the list
of subcommand should be generated. Only has an effect
if the C{subCommands} attribute has been defined on the
L{twisted.python.usage.Options} instance. | write | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | MIT |
def write(self):
"""
Generate the completion function and write it to the output file
@return: L{None}
"""
gen = ZshArgumentsGenerator(self.options, self.cmdName, self.file)
gen.extraActions.insert(0, SubcommandAction())
gen.write()
gen = ZshArgumentsGenerator(self.subOptions, self.cmdName, self.file)
gen.write() | Generate the completion function and write it to the output file
@return: L{None} | write | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | MIT |
def write(self):
"""
Write the zsh completion code to the file given to __init__
@return: L{None}
"""
self.writeHeader()
self.writeExtras()
self.writeOptions()
self.writeFooter() | Write the zsh completion code to the file given to __init__
@return: L{None} | write | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | MIT |
def writeHeader(self):
"""
This is the start of the code that calls _arguments
@return: L{None}
"""
self.file.write(b'#compdef ' + self.cmdName.encode('utf-8') +
b'\n\n'
b'_arguments -s -A "-*" \\\n') | This is the start of the code that calls _arguments
@return: L{None} | writeHeader | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | MIT |
def writeOptions(self):
"""
Write out zsh code for each option in this command
@return: L{None}
"""
optNames = list(self.allOptionsNameToDefinition.keys())
optNames.sort()
for longname in optNames:
self.writeOpt(longname) | Write out zsh code for each option in this command
@return: L{None} | writeOptions | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | MIT |
def writeExtras(self):
"""
Write out completion information for extra arguments appearing on the
command-line. These are extra positional arguments not associated
with a named option. That is, the stuff that gets passed to
Options.parseArgs().
@return: L{None}
@raises: ValueError: if C{Completer} with C{repeat=True} is found and
is not the last item in the C{extraActions} list.
"""
for i, action in enumerate(self.extraActions):
# a repeatable action must be the last action in the list
if action._repeat and i != len(self.extraActions) - 1:
raise ValueError("Completer with repeat=True must be "
"last item in Options.extraActions")
self.file.write(
escape(action._shellCode('', usage._ZSH)).encode('utf-8'))
self.file.write(b' \\\n') | Write out completion information for extra arguments appearing on the
command-line. These are extra positional arguments not associated
with a named option. That is, the stuff that gets passed to
Options.parseArgs().
@return: L{None}
@raises: ValueError: if C{Completer} with C{repeat=True} is found and
is not the last item in the C{extraActions} list. | writeExtras | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | MIT |
def writeFooter(self):
"""
Write the last bit of code that finishes the call to _arguments
@return: L{None}
"""
self.file.write(b'&& return 0\n') | Write the last bit of code that finishes the call to _arguments
@return: L{None} | writeFooter | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | MIT |
def verifyZshNames(self):
"""
Ensure that none of the option names given in the metadata are typoed
@return: L{None}
@raise ValueError: Raised if unknown option names have been found.
"""
def err(name):
raise ValueError("Unknown option name \"%s\" found while\n"
"examining Completions instances on %s" % (
name, self.options))
for name in itertools.chain(self.descriptions, self.optActions,
self.multiUse):
if name not in self.allOptionsNameToDefinition:
err(name)
for seq in self.mutuallyExclusive:
for name in seq:
if name not in self.allOptionsNameToDefinition:
err(name) | Ensure that none of the option names given in the metadata are typoed
@return: L{None}
@raise ValueError: Raised if unknown option names have been found. | verifyZshNames | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | MIT |
def excludeStr(self, longname, buildShort=False):
"""
Generate an "exclusion string" for the given option
@type longname: C{str}
@param longname: The long option name (e.g. "verbose" instead of "v")
@type buildShort: C{bool}
@param buildShort: May be True to indicate we're building an excludes
string for the short option that corresponds to the given long opt.
@return: The generated C{str}
"""
if longname in self.excludes:
exclusions = self.excludes[longname].copy()
else:
exclusions = set()
# if longname isn't a multiUse option (can't appear on the cmd line more
# than once), then we have to exclude the short option if we're
# building for the long option, and vice versa.
if longname not in self.multiUse:
if buildShort is False:
short = self.getShortOption(longname)
if short is not None:
exclusions.add(short)
else:
exclusions.add(longname)
if not exclusions:
return ''
strings = []
for optName in exclusions:
if len(optName) == 1:
# short option
strings.append("-" + optName)
else:
strings.append("--" + optName)
strings.sort() # need deterministic order for reliable unit-tests
return "(%s)" % " ".join(strings) | Generate an "exclusion string" for the given option
@type longname: C{str}
@param longname: The long option name (e.g. "verbose" instead of "v")
@type buildShort: C{bool}
@param buildShort: May be True to indicate we're building an excludes
string for the short option that corresponds to the given long opt.
@return: The generated C{str} | excludeStr | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | MIT |
def makeExcludesDict(self):
"""
@return: A C{dict} that maps each option name appearing in
self.mutuallyExclusive to a list of those option names that is it
mutually exclusive with (can't appear on the cmd line with).
"""
#create a mapping of long option name -> single character name
longToShort = {}
for optList in itertools.chain(self.optParams, self.optFlags):
if optList[1] != None:
longToShort[optList[0]] = optList[1]
excludes = {}
for lst in self.mutuallyExclusive:
for i, longname in enumerate(lst):
tmp = set(lst[:i] + lst[i+1:])
for name in tmp.copy():
if name in longToShort:
tmp.add(longToShort[name])
if longname in excludes:
excludes[longname] = excludes[longname].union(tmp)
else:
excludes[longname] = tmp
return excludes | @return: A C{dict} that maps each option name appearing in
self.mutuallyExclusive to a list of those option names that is it
mutually exclusive with (can't appear on the cmd line with). | makeExcludesDict | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | MIT |
def writeOpt(self, longname):
"""
Write out the zsh code for the given argument. This is just part of the
one big call to _arguments
@type longname: C{str}
@param longname: The long option name (e.g. "verbose" instead of "v")
@return: L{None}
"""
if longname in self.flagNameToDefinition:
# It's a flag option. Not one that takes a parameter.
longField = "--%s" % longname
else:
longField = "--%s=" % longname
short = self.getShortOption(longname)
if short != None:
shortField = "-" + short
else:
shortField = ''
descr = self.getDescription(longname)
descriptionField = descr.replace("[", "\[")
descriptionField = descriptionField.replace("]", "\]")
descriptionField = '[%s]' % descriptionField
actionField = self.getAction(longname)
if longname in self.multiUse:
multiField = '*'
else:
multiField = ''
longExclusionsField = self.excludeStr(longname)
if short:
#we have to write an extra line for the short option if we have one
shortExclusionsField = self.excludeStr(longname, buildShort=True)
self.file.write(escape('%s%s%s%s%s' % (shortExclusionsField,
multiField, shortField, descriptionField, actionField)).encode('utf-8'))
self.file.write(b' \\\n')
self.file.write(escape('%s%s%s%s%s' % (longExclusionsField,
multiField, longField, descriptionField, actionField)).encode('utf-8'))
self.file.write(b' \\\n') | Write out the zsh code for the given argument. This is just part of the
one big call to _arguments
@type longname: C{str}
@param longname: The long option name (e.g. "verbose" instead of "v")
@return: L{None} | writeOpt | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | MIT |
def getAction(self, longname):
"""
Return a zsh "action" string for the given argument
@return: C{str}
"""
if longname in self.optActions:
if callable(self.optActions[longname]):
action = self.optActions[longname]()
else:
action = self.optActions[longname]
return action._shellCode(longname, usage._ZSH)
if longname in self.paramNameToDefinition:
return ':%s:_files' % (longname,)
return '' | Return a zsh "action" string for the given argument
@return: C{str} | getAction | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | MIT |
def getDescription(self, longname):
"""
Return the description to be used for this argument
@return: C{str}
"""
#check if we have an alternate descr for this arg, and if so use it
if longname in self.descriptions:
return self.descriptions[longname]
#otherwise we have to get it from the optFlags or optParams
try:
descr = self.flagNameToDefinition[longname][1]
except KeyError:
try:
descr = self.paramNameToDefinition[longname][2]
except KeyError:
descr = None
if descr is not None:
return descr
# let's try to get it from the opt_foo method doc string if there is one
longMangled = longname.replace('-', '_') # this is what t.p.usage does
obj = getattr(self.options, 'opt_%s' % longMangled, None)
if obj is not None:
descr = descrFromDoc(obj)
if descr is not None:
return descr
return longname # we really ought to have a good description to use | Return the description to be used for this argument
@return: C{str} | getDescription | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | MIT |
def getShortOption(self, longname):
"""
Return the short option letter or None
@return: C{str} or L{None}
"""
optList = self.allOptionsNameToDefinition[longname]
return optList[0] or None | Return the short option letter or None
@return: C{str} or L{None} | getShortOption | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | MIT |
def addAdditionalOptions(self):
"""
Add additional options to the optFlags and optParams lists.
These will be defined by 'opt_foo' methods of the Options subclass
@return: L{None}
"""
methodsDict = {}
reflect.accumulateMethods(self.options, methodsDict, 'opt_')
methodToShort = {}
for name in methodsDict.copy():
if len(name) == 1:
methodToShort[methodsDict[name]] = name
del methodsDict[name]
for methodName, methodObj in methodsDict.items():
longname = methodName.replace('_', '-') # t.p.usage does this
# if this option is already defined by the optFlags or
# optParameters then we don't want to override that data
if longname in self.allOptionsNameToDefinition:
continue
descr = self.getDescription(longname)
short = None
if methodObj in methodToShort:
short = methodToShort[methodObj]
reqArgs = methodObj.__func__.__code__.co_argcount
if reqArgs == 2:
self.optParams.append([longname, short, None, descr])
self.paramNameToDefinition[longname] = [short, None, descr]
self.allOptionsNameToDefinition[longname] = [short, None, descr]
else:
# reqArgs must equal 1. self.options would have failed
# to instantiate if it had opt_ methods with bad signatures.
self.optFlags.append([longname, short, descr])
self.flagNameToDefinition[longname] = [short, descr]
self.allOptionsNameToDefinition[longname] = [short, None, descr] | Add additional options to the optFlags and optParams lists.
These will be defined by 'opt_foo' methods of the Options subclass
@return: L{None} | addAdditionalOptions | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | MIT |
def descrFromDoc(obj):
"""
Generate an appropriate description from docstring of the given object
"""
if obj.__doc__ is None or obj.__doc__.isspace():
return None
lines = [x.strip() for x in obj.__doc__.split("\n")
if x and not x.isspace()]
return " ".join(lines) | Generate an appropriate description from docstring of the given object | descrFromDoc | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | MIT |
def escape(x):
"""
Shell escape the given string
Implementation borrowed from now-deprecated commands.mkarg() in the stdlib
"""
if '\'' not in x:
return '\'' + x + '\''
s = '"'
for c in x:
if c in '\\$"`':
s = s + '\\'
s = s + c
s = s + '"'
return s | Shell escape the given string
Implementation borrowed from now-deprecated commands.mkarg() in the stdlib | escape | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_shellcomp.py | MIT |
def prefixedMethodNames(classObj, prefix):
"""
Given a class object C{classObj}, returns a list of method names that match
the string C{prefix}.
@param classObj: A class object from which to collect method names.
@param prefix: A native string giving a prefix. Each method with a name
which begins with this prefix will be returned.
@type prefix: L{str}
@return: A list of the names of matching methods of C{classObj} (and base
classes of C{classObj}).
@rtype: L{list} of L{str}
"""
dct = {}
addMethodNamesToDict(classObj, dct, prefix)
return list(dct.keys()) | Given a class object C{classObj}, returns a list of method names that match
the string C{prefix}.
@param classObj: A class object from which to collect method names.
@param prefix: A native string giving a prefix. Each method with a name
which begins with this prefix will be returned.
@type prefix: L{str}
@return: A list of the names of matching methods of C{classObj} (and base
classes of C{classObj}).
@rtype: L{list} of L{str} | prefixedMethodNames | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | MIT |
def addMethodNamesToDict(classObj, dict, prefix, baseClass=None):
"""
This goes through C{classObj} (and its bases) and puts method names
starting with 'prefix' in 'dict' with a value of 1. if baseClass isn't
None, methods will only be added if classObj is-a baseClass
If the class in question has the methods 'prefix_methodname' and
'prefix_methodname2', the resulting dict should look something like:
{"methodname": 1, "methodname2": 1}.
@param classObj: A class object from which to collect method names.
@param dict: A L{dict} which will be updated with the results of the
accumulation. Items are added to this dictionary, with method names as
keys and C{1} as values.
@type dict: L{dict}
@param prefix: A native string giving a prefix. Each method of C{classObj}
(and base classes of C{classObj}) with a name which begins with this
prefix will be returned.
@type prefix: L{str}
@param baseClass: A class object at which to stop searching upwards for new
methods. To collect all method names, do not pass a value for this
parameter.
@return: L{None}
"""
for base in classObj.__bases__:
addMethodNamesToDict(base, dict, prefix, baseClass)
if baseClass is None or baseClass in classObj.__bases__:
for name, method in classObj.__dict__.items():
optName = name[len(prefix):]
if ((type(method) is types.FunctionType)
and (name[:len(prefix)] == prefix)
and (len(optName))):
dict[optName] = 1 | This goes through C{classObj} (and its bases) and puts method names
starting with 'prefix' in 'dict' with a value of 1. if baseClass isn't
None, methods will only be added if classObj is-a baseClass
If the class in question has the methods 'prefix_methodname' and
'prefix_methodname2', the resulting dict should look something like:
{"methodname": 1, "methodname2": 1}.
@param classObj: A class object from which to collect method names.
@param dict: A L{dict} which will be updated with the results of the
accumulation. Items are added to this dictionary, with method names as
keys and C{1} as values.
@type dict: L{dict}
@param prefix: A native string giving a prefix. Each method of C{classObj}
(and base classes of C{classObj}) with a name which begins with this
prefix will be returned.
@type prefix: L{str}
@param baseClass: A class object at which to stop searching upwards for new
methods. To collect all method names, do not pass a value for this
parameter.
@return: L{None} | addMethodNamesToDict | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | MIT |
def prefixedMethods(obj, prefix=''):
"""
Given an object C{obj}, returns a list of method objects that match the
string C{prefix}.
@param obj: An arbitrary object from which to collect methods.
@param prefix: A native string giving a prefix. Each method of C{obj} with
a name which begins with this prefix will be returned.
@type prefix: L{str}
@return: A list of the matching method objects.
@rtype: L{list}
"""
dct = {}
accumulateMethods(obj, dct, prefix)
return list(dct.values()) | Given an object C{obj}, returns a list of method objects that match the
string C{prefix}.
@param obj: An arbitrary object from which to collect methods.
@param prefix: A native string giving a prefix. Each method of C{obj} with
a name which begins with this prefix will be returned.
@type prefix: L{str}
@return: A list of the matching method objects.
@rtype: L{list} | prefixedMethods | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | MIT |
def accumulateMethods(obj, dict, prefix='', curClass=None):
"""
Given an object C{obj}, add all methods that begin with C{prefix}.
@param obj: An arbitrary object to collect methods from.
@param dict: A L{dict} which will be updated with the results of the
accumulation. Items are added to this dictionary, with method names as
keys and corresponding instance method objects as values.
@type dict: L{dict}
@param prefix: A native string giving a prefix. Each method of C{obj} with
a name which begins with this prefix will be returned.
@type prefix: L{str}
@param curClass: The class in the inheritance hierarchy at which to start
collecting methods. Collection proceeds up. To collect all methods
from C{obj}, do not pass a value for this parameter.
@return: L{None}
"""
if not curClass:
curClass = obj.__class__
for base in curClass.__bases__:
# The implementation of the object class is different on PyPy vs.
# CPython. This has the side effect of making accumulateMethods()
# pick up object methods from all new-style classes -
# such as __getattribute__, etc.
# If we ignore 'object' when accumulating methods, we can get
# consistent behavior on Pypy and CPython.
if base is not object:
accumulateMethods(obj, dict, prefix, base)
for name, method in curClass.__dict__.items():
optName = name[len(prefix):]
if ((type(method) is types.FunctionType)
and (name[:len(prefix)] == prefix)
and (len(optName))):
dict[optName] = getattr(obj, name) | Given an object C{obj}, add all methods that begin with C{prefix}.
@param obj: An arbitrary object to collect methods from.
@param dict: A L{dict} which will be updated with the results of the
accumulation. Items are added to this dictionary, with method names as
keys and corresponding instance method objects as values.
@type dict: L{dict}
@param prefix: A native string giving a prefix. Each method of C{obj} with
a name which begins with this prefix will be returned.
@type prefix: L{str}
@param curClass: The class in the inheritance hierarchy at which to start
collecting methods. Collection proceeds up. To collect all methods
from C{obj}, do not pass a value for this parameter.
@return: L{None} | accumulateMethods | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | MIT |
def namedModule(name):
"""
Return a module given its name.
"""
topLevel = __import__(name)
packages = name.split(".")[1:]
m = topLevel
for p in packages:
m = getattr(m, p)
return m | Return a module given its name. | namedModule | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | MIT |
def namedObject(name):
"""
Get a fully named module-global object.
"""
classSplit = name.split('.')
module = namedModule('.'.join(classSplit[:-1]))
return getattr(module, classSplit[-1]) | Get a fully named module-global object. | namedObject | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | MIT |
def requireModule(name, default=None):
"""
Try to import a module given its name, returning C{default} value if
C{ImportError} is raised during import.
@param name: Module name as it would have been passed to C{import}.
@type name: C{str}.
@param default: Value returned in case C{ImportError} is raised while
importing the module.
@return: Module or default value.
"""
try:
return namedModule(name)
except ImportError:
return default | Try to import a module given its name, returning C{default} value if
C{ImportError} is raised during import.
@param name: Module name as it would have been passed to C{import}.
@type name: C{str}.
@param default: Value returned in case C{ImportError} is raised while
importing the module.
@return: Module or default value. | requireModule | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | MIT |
def _importAndCheckStack(importName):
"""
Import the given name as a module, then walk the stack to determine whether
the failure was the module not existing, or some code in the module (for
example a dependent import) failing. This can be helpful to determine
whether any actual application code was run. For example, to distiguish
administrative error (entering the wrong module name), from programmer
error (writing buggy code in a module that fails to import).
@param importName: The name of the module to import.
@type importName: C{str}
@raise Exception: if something bad happens. This can be any type of
exception, since nobody knows what loading some arbitrary code might
do.
@raise _NoModuleFound: if no module was found.
"""
try:
return __import__(importName)
except ImportError:
excType, excValue, excTraceback = sys.exc_info()
while excTraceback:
execName = excTraceback.tb_frame.f_globals["__name__"]
# in Python 2 execName is None when an ImportError is encountered,
# where in Python 3 execName is equal to the importName.
if execName is None or execName == importName:
reraise(excValue, excTraceback)
excTraceback = excTraceback.tb_next
raise _NoModuleFound() | Import the given name as a module, then walk the stack to determine whether
the failure was the module not existing, or some code in the module (for
example a dependent import) failing. This can be helpful to determine
whether any actual application code was run. For example, to distiguish
administrative error (entering the wrong module name), from programmer
error (writing buggy code in a module that fails to import).
@param importName: The name of the module to import.
@type importName: C{str}
@raise Exception: if something bad happens. This can be any type of
exception, since nobody knows what loading some arbitrary code might
do.
@raise _NoModuleFound: if no module was found. | _importAndCheckStack | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | MIT |
def namedAny(name):
"""
Retrieve a Python object by its fully qualified name from the global Python
module namespace. The first part of the name, that describes a module,
will be discovered and imported. Each subsequent part of the name is
treated as the name of an attribute of the object specified by all of the
name which came before it. For example, the fully-qualified name of this
object is 'twisted.python.reflect.namedAny'.
@type name: L{str}
@param name: The name of the object to return.
@raise InvalidName: If the name is an empty string, starts or ends with
a '.', or is otherwise syntactically incorrect.
@raise ModuleNotFound: If the name is syntactically correct but the
module it specifies cannot be imported because it does not appear to
exist.
@raise ObjectNotFound: If the name is syntactically correct, includes at
least one '.', but the module it specifies cannot be imported because
it does not appear to exist.
@raise AttributeError: If an attribute of an object along the way cannot be
accessed, or a module along the way is not found.
@return: the Python object identified by 'name'.
"""
if not name:
raise InvalidName('Empty module name')
names = name.split('.')
# if the name starts or ends with a '.' or contains '..', the __import__
# will raise an 'Empty module name' error. This will provide a better error
# message.
if '' in names:
raise InvalidName(
"name must be a string giving a '.'-separated list of Python "
"identifiers, not %r" % (name,))
topLevelPackage = None
moduleNames = names[:]
while not topLevelPackage:
if moduleNames:
trialname = '.'.join(moduleNames)
try:
topLevelPackage = _importAndCheckStack(trialname)
except _NoModuleFound:
moduleNames.pop()
else:
if len(names) == 1:
raise ModuleNotFound("No module named %r" % (name,))
else:
raise ObjectNotFound('%r does not name an object' % (name,))
obj = topLevelPackage
for n in names[1:]:
obj = getattr(obj, n)
return obj | Retrieve a Python object by its fully qualified name from the global Python
module namespace. The first part of the name, that describes a module,
will be discovered and imported. Each subsequent part of the name is
treated as the name of an attribute of the object specified by all of the
name which came before it. For example, the fully-qualified name of this
object is 'twisted.python.reflect.namedAny'.
@type name: L{str}
@param name: The name of the object to return.
@raise InvalidName: If the name is an empty string, starts or ends with
a '.', or is otherwise syntactically incorrect.
@raise ModuleNotFound: If the name is syntactically correct but the
module it specifies cannot be imported because it does not appear to
exist.
@raise ObjectNotFound: If the name is syntactically correct, includes at
least one '.', but the module it specifies cannot be imported because
it does not appear to exist.
@raise AttributeError: If an attribute of an object along the way cannot be
accessed, or a module along the way is not found.
@return: the Python object identified by 'name'. | namedAny | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | MIT |
def filenameToModuleName(fn):
"""
Convert a name in the filesystem to the name of the Python module it is.
This is aggressive about getting a module name back from a file; it will
always return a string. Aggressive means 'sometimes wrong'; it won't look
at the Python path or try to do any error checking: don't use this method
unless you already know that the filename you're talking about is a Python
module.
@param fn: A filesystem path to a module or package; C{bytes} on Python 2,
C{bytes} or C{unicode} on Python 3.
@return: A hopefully importable module name.
@rtype: C{str}
"""
if isinstance(fn, bytes):
initPy = b"__init__.py"
else:
initPy = "__init__.py"
fullName = os.path.abspath(fn)
base = os.path.basename(fn)
if not base:
# this happens when fn ends with a path separator, just skit it
base = os.path.basename(fn[:-1])
modName = nativeString(os.path.splitext(base)[0])
while 1:
fullName = os.path.dirname(fullName)
if os.path.exists(os.path.join(fullName, initPy)):
modName = "%s.%s" % (
nativeString(os.path.basename(fullName)),
nativeString(modName))
else:
break
return modName | Convert a name in the filesystem to the name of the Python module it is.
This is aggressive about getting a module name back from a file; it will
always return a string. Aggressive means 'sometimes wrong'; it won't look
at the Python path or try to do any error checking: don't use this method
unless you already know that the filename you're talking about is a Python
module.
@param fn: A filesystem path to a module or package; C{bytes} on Python 2,
C{bytes} or C{unicode} on Python 3.
@return: A hopefully importable module name.
@rtype: C{str} | filenameToModuleName | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | MIT |
def qual(clazz):
"""
Return full import path of a class.
"""
return clazz.__module__ + '.' + clazz.__name__ | Return full import path of a class. | qual | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | MIT |
def _safeFormat(formatter, o):
"""
Helper function for L{safe_repr} and L{safe_str}.
Called when C{repr} or C{str} fail. Returns a string containing info about
C{o} and the latest exception.
@param formatter: C{str} or C{repr}.
@type formatter: C{type}
@param o: Any object.
@rtype: C{str}
@return: A string containing information about C{o} and the raised
exception.
"""
io = NativeStringIO()
traceback.print_exc(file=io)
className = _determineClassName(o)
tbValue = io.getvalue()
return "<%s instance at 0x%x with %s error:\n %s>" % (
className, id(o), formatter.__name__, tbValue) | Helper function for L{safe_repr} and L{safe_str}.
Called when C{repr} or C{str} fail. Returns a string containing info about
C{o} and the latest exception.
@param formatter: C{str} or C{repr}.
@type formatter: C{type}
@param o: Any object.
@rtype: C{str}
@return: A string containing information about C{o} and the raised
exception. | _safeFormat | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | MIT |
def safe_repr(o):
"""
Returns a string representation of an object, or a string containing a
traceback, if that object's __repr__ raised an exception.
@param o: Any object.
@rtype: C{str}
"""
try:
return repr(o)
except:
return _safeFormat(repr, o) | Returns a string representation of an object, or a string containing a
traceback, if that object's __repr__ raised an exception.
@param o: Any object.
@rtype: C{str} | safe_repr | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | MIT |
def safe_str(o):
"""
Returns a string representation of an object, or a string containing a
traceback, if that object's __str__ raised an exception.
@param o: Any object.
@rtype: C{str}
"""
if _PY3 and isinstance(o, bytes):
# If o is bytes and seems to holds a utf-8 encoded string,
# convert it to str.
try:
return o.decode('utf-8')
except:
pass
try:
return str(o)
except:
return _safeFormat(str, o) | Returns a string representation of an object, or a string containing a
traceback, if that object's __str__ raised an exception.
@param o: Any object.
@rtype: C{str} | safe_str | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | MIT |
def getClass(obj):
"""
Return the class or type of object 'obj'.
Returns sensible result for oldstyle and newstyle instances and types.
"""
if hasattr(obj, '__class__'):
return obj.__class__
else:
return type(obj) | Return the class or type of object 'obj'.
Returns sensible result for oldstyle and newstyle instances and types. | getClass | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/reflect.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.