本文整理汇总了Python中twisted.python.reflect.namedModule函数的典型用法代码示例。如果您正苦于以下问题:Python namedModule函数的具体用法?Python namedModule怎么用?Python namedModule使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了namedModule函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _accept_slave
def _accept_slave(res):
self.slave_status.setConnected(True)
self.slave_status.updateInfo(
admin=state.get("admin"),
host=state.get("host"),
access_uri=state.get("access_uri"),
version=state.get("version"),
)
self.slave_commands = state.get("slave_commands")
self.slave_environ = state.get("slave_environ")
self.slave_basedir = state.get("slave_basedir")
self.slave_system = state.get("slave_system")
self.slave = bot
if self.slave_system == "nt":
self.path_module = namedModule("ntpath")
else:
# most everything accepts / as separator, so posix should be a
# reasonable fallback
self.path_module = namedModule("posixpath")
log.msg("bot attached")
self.messageReceivedFromSlave()
self.stopMissingTimer()
self.botmaster.master.status.slaveConnected(self.slavename)
示例2: changeWorkerSystem
def changeWorkerSystem(self, system):
self.worker.worker_system = system
if system in ['nt', 'win32']:
self.build.path_module = namedModule('ntpath')
self.worker.worker_basedir = '\\wrk'
else:
self.build.path_module = namedModule('posixpath')
self.worker.worker_basedir = '/wrk'
示例3: testCompatibility
def testCompatibility(self):
for oldName, newName in movedModules:
try:
old = reflect.namedModule(oldName)
new = reflect.namedModule(newName)
except ImportError, e:
continue
for someName in [x for x in vars(new).keys() if x != '__doc__']:
self.assertIdentical(getattr(old, someName),
getattr(new, someName))
示例4: runApp
def runApp(config):
global initRun
platformType = runtime.platform.getType()
sys.path.append(config['rundir'])
# Install a reactor immediately. The application will not load properly
# unless this is done FIRST; otherwise the first 'reactor' import would
# trigger an automatic installation of the default reactor.
# To make this callable from within a running Twisted app, allow as the
# reactor None to bypass this and use whatever reactor is currently in use.
if config['reactor']:
if platformType == 'java':
from twisted.internet import javareactor
javareactor.install()
else:
from twisted.python.reflect import namedModule
namedModule(reactorTypes[config['reactor']]).install()
if platformType != 'posix' or config['debug']:
# only posix can fork, and debugging requires nodaemon
config['nodaemon'] = 1
if config['encrypted']:
import getpass
passphrase = getpass.getpass('Passphrase: ')
else:
passphrase = None
# Load the servers.
# This will fix up accidental function definitions in evaluation spaces
# and the like.
initRun = 0
if os.path.exists(config['pidfile']):
try:
pid = int(open(config['pidfile']).read())
except ValueError:
sys.exit('Pidfile %s contains non numeric value' % config['pidfile'])
try:
os.kill(pid, 0)
except OSError, why:
if why[0] == errno.ESRCH:
# The pid doesnt exists.
if not config['quiet']:
print 'Removing stale pidfile %s' % config['pidfile']
os.remove(config['pidfile'])
else:
sys.exit('Can\'t check status of PID %s from pidfile %s: %s' % (pid, config['pidfile'], why[1]))
except AttributeError:
pass # welcome to windows
示例5: test_importQtreactor
def test_importQtreactor(self):
"""
Attempting to import L{twisted.internet.qtreactor} should raise an
C{ImportError} indicating that C{qtreactor} is no longer a part of
Twisted.
"""
sys.modules["qtreactor"] = None
from twisted.plugins.twisted_qtstub import errorMessage
try:
namedModule('twisted.internet.qtreactor')
except ImportError, e:
self.assertEqual(str(e), errorMessage)
示例6: attached
def attached(self, conn):
"""This is called when the worker connects."""
metrics.MetricCountEvent.log("AbstractWorker.attached_workers", 1)
# now we go through a sequence of calls, gathering information, then
# tell the Botmaster that it can finally give this worker to all the
# Builders that care about it.
# Reset graceful shutdown status
self.worker_status.setGraceful(False)
# We want to know when the graceful shutdown flag changes
self.worker_status.addGracefulWatcher(self._gracefulChanged)
self.conn = conn
self._old_builder_list = None # clear builder list before proceed
self.worker_status.addPauseWatcher(self._pauseChanged)
self.worker_status.setConnected(True)
self._applyWorkerInfo(conn.info)
self.worker_commands = conn.info.get("slave_commands", {})
self.worker_environ = conn.info.get("environ", {})
self.worker_basedir = conn.info.get("basedir", None)
self.worker_system = conn.info.get("system", None)
self.conn.notifyOnDisconnect(self.detached)
workerinfo = {
'admin': conn.info.get('admin'),
'host': conn.info.get('host'),
'access_uri': conn.info.get('access_uri'),
'version': conn.info.get('version')
}
yield self.master.data.updates.workerConnected(
workerid=self.workerid,
masterid=self.master.masterid,
workerinfo=workerinfo
)
if self.worker_system == "nt":
self.path_module = namedModule("ntpath")
else:
# most everything accepts / as separator, so posix should be a
# reasonable fallback
self.path_module = namedModule("posixpath")
log.msg("bot attached")
self.messageReceivedFromWorker()
self.stopMissingTimer()
self.master.status.workerConnected(self.name)
yield self.updateWorker()
yield self.botmaster.maybeStartBuildsForWorker(self.name)
示例7: test_supportsThreads
def test_supportsThreads(self):
"""
L{Platform.supportsThreads} returns C{True} if threads can be created in
this runtime, C{False} otherwise.
"""
# It's difficult to test both cases of this without faking the threading
# module. Perhaps an adequate test is to just test the behavior with
# the current runtime, whatever that happens to be.
try:
namedModule('threading')
except ImportError:
self.assertFalse(Platform().supportsThreads())
else:
self.assertTrue(Platform().supportsThreads())
示例8: processComponent
def processComponent (componentName, v):
if collectionName is not None:
componentName = "{:s}/{:s}".format(collectionName, componentName)
# It's a class
if IComponent.implementedBy(v):
fileName = namedModule(v.__module__).__file__
objectName = "{:s}.{:s}".format(v.__module__, v.__name__)
component = v()
# It's a function (eg getComponent)
elif callable(v):
fileName = namedModule(v.__module__).__file__
objectName = "{:s}.{:s}".format(v.__module__, v.__name__)
component = v()
if not IComponent.providedBy(component):
raise Error(
"{:s}.{:s}() does not produce a valid Component".format(
v.__module__,
v.__name__
))
# It's a string - hopefully a '.fbp' or '.json'
else:
import graph
fileName = os.path.join(moduleDir, str(v))
objectName = None
component = graph.loadFile(fileName)
if not IComponent.providedBy(component):
raise Error(
"{:s} does not produce a valid Component".format(
componentName
))
# Make sure we will check the ".py" file
if fileName[-4:] == ".pyc":
fileName = fileName[:-1]
if component.ready:
return defer.succeed((fileName, objectName, componentName, component))
else:
d = defer.Deferred()
component.once("ready", lambda data: d.callback(
(fileName, objectName, componentName, component)
))
return d
示例9: addPackageRecursive
def addPackageRecursive(self, package):
if type(package) is types.StringType:
try:
package = reflect.namedModule(package)
except ImportError, e:
self.couldNotImport[package] = e
return
示例10: __init__
def __init__(self, dbapiName, *connargs, **connkw):
"""See ConnectionPool.__doc__
"""
self.dbapiName = dbapiName
if self.noisy:
log.msg("Connecting to database: %s %s %s" % (dbapiName, connargs, connkw))
self.dbapi = reflect.namedModule(dbapiName)
assert self.dbapi.apilevel == '2.0', 'DB API module not DB API 2.0 compliant.'
assert self.dbapi.threadsafety > 0, 'DB API module not sufficiently thread-safe.'
self.connargs = connargs
self.connkw = connkw
import thread
self.threadID = thread.get_ident
self.connections = {}
if connkw.has_key('cp_min'):
min = connkw['cp_min']
del connkw['cp_min']
else:
min = 3
if connkw.has_key('cp_max'):
max = connkw['cp_max']
del connkw['cp_max']
else:
max = 5
from twisted.internet import reactor
self.shutdownID = reactor.addSystemEventTrigger('during', 'shutdown', self.finalClose)
示例11: executePolicyDir
def executePolicyDir(func, d, prefix=None):
"""
Execute all .py files in a directory, in alphabetical order, calling func on the module
This throws a TryError if any of the modules fail. The result is a list of tuples consisting
of the module name and str rep of the exception
"""
##
# a bit cheap but we want to temporarily make this direcotry in our path if it isn't already
# so safe out sys.path, add d to it, and put it back when done
oldpath = sys.path
sys.path = [d] + sys.path
path = d
if prefix:
path = os.path.join(path, prefix)
files = [f[:-3]
for f in os.listdir(path)
if f.endswith('.py') and f != '__init__.py']
files.sort()
errorRes = []
try:
for f in files:
if prefix:
f = prefix + '.' + f
try:
m = namedModule(f)
func(m)
except Exception, err:
errorRes.append((f, str(err), getStacktrace()))
finally:
sys.path = oldpath
if errorRes:
raise TryError('Failed to execute all modules', errorRes)
示例12: remote_registerClasses
def remote_registerClasses(self, *args):
"""
Instructs my broker to register the classes specified by the
argument(s).
The classes will be registered for B{all} jobs, and are specified by
their string representations::
<package(s).module.class>
"""
modules = []
for stringRep in args:
# Load the class for the string representation
cls = reflect.namedObject(stringRep)
# Register instances of the class, including its type and module
pb.setUnjellyableForClass(stringRep, cls)
if cls.__module__ not in modules:
modules.append(cls.__module__)
# Try to build the modules for the classes in case they've changed
# since the last run
for module in modules:
try:
rebuild(reflect.namedModule(module), doLog=False)
except:
pass
示例13: _getSuite
def _getSuite(config):
def _dbg(msg):
log.msg(iface=itrial.ITrialDebug, parseargs=msg)
reporterKlass = _getReporter(config)
log.msg(iface=ITrialDebug, reporter="using reporter reporterKlass: %r" % (reporterKlass,))
suite = runner.TestSuite(reporterKlass(
tbformat=config['tbformat'],
args=config['reporter-args'],
realtime=config['rterrors']),
_getJanitor(),
benchmark=config['benchmark'])
suite.couldNotImport.update(config['_couldNotImport'])
suite.dryRun = config['dry-run']
for package in config['packages']:
if isinstance(package, types.StringType):
try:
package = reflect.namedModule(package)
except ImportError, e:
suite.couldNotImport[package] = failure.Failure()
continue
if config['recurse']:
_dbg("addPackageRecursive(%s)" % (package,))
suite.addPackageRecursive(package)
else:
_dbg("addPackage(%s)" % (package,))
suite.addPackage(package)
示例14: test_scanModule
def test_scanModule(self):
# use this module as a test
mod = reflect.namedModule('buildbot.test.unit.test_data_connector')
self.data._scanModule(mod)
# check that it discovered MyResourceType and updated endpoints
match = self.data.matcher[('test', '10')]
self.assertIsInstance(match[0], TestEndpoint)
self.assertEqual(match[1], dict(testid=10))
match = self.data.matcher[('test', '10', 'p1')]
self.assertIsInstance(match[0], TestEndpoint)
match = self.data.matcher[('test', '10', 'p2')]
self.assertIsInstance(match[0], TestEndpoint)
match = self.data.matcher[('test',)]
self.assertIsInstance(match[0], TestsEndpoint)
self.assertEqual(match[1], dict())
match = self.data.matcher[('test', 'foo')]
self.assertIsInstance(match[0], TestsEndpointSubclass)
self.assertEqual(match[1], dict())
# and that it found the update method
self.assertEqual(self.data.updates.testUpdate(), "testUpdate return")
# and that it added the single root link
self.assertEqual(self.data.rootLinks,
[{'name': 'tests'}])
# and that it added an attribute
self.assertIsInstance(self.data.rtypes.test, TestResourceType)
示例15: moduleMovedForSplit
def moduleMovedForSplit(origModuleName, newModuleName, moduleDesc,
projectName, projectURL, globDict):
from twisted.python import reflect
modoc = """
%(moduleDesc)s
This module is DEPRECATED. It has been split off into a third party
package, Twisted %(projectName)s. Please see %(projectURL)s.
This is just a place-holder that imports from the third-party %(projectName)s
package for backwards compatibility. To use it, you need to install
that package.
""" % {'moduleDesc': moduleDesc,
'projectName': projectName,
'projectURL': projectURL}
#origModule = reflect.namedModule(origModuleName)
try:
newModule = reflect.namedModule(newModuleName)
except ImportError:
raise ImportError("You need to have the Twisted %s "
"package installed to use %s. "
"See %s."
% (projectName, origModuleName, projectURL))
# Populate the old module with the new module's contents
for k,v in vars(newModule).items():
globDict[k] = v
globDict['__doc__'] = modoc
import warnings
warnings.warn("%s has moved to %s. See %s." % (origModuleName, newModuleName,
projectURL),
DeprecationWarning, stacklevel=3)
return