当前位置: 首页>>代码示例>>Python>>正文


Python DeferredLock.run方法代码示例

本文整理汇总了Python中twisted.internet.defer.DeferredLock.run方法的典型用法代码示例。如果您正苦于以下问题:Python DeferredLock.run方法的具体用法?Python DeferredLock.run怎么用?Python DeferredLock.run使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twisted.internet.defer.DeferredLock的用法示例。


在下文中一共展示了DeferredLock.run方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: MKSPDR2000Wrapper

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import run [as 别名]
class MKSPDR2000Wrapper(DeviceWrapper):
    @inlineCallbacks
    def connect(self, server, port):
        '''Connect to the MKS PDR2000'''
        print('Connecting to "%s" on port "%s"...' %(server.name, port))

        self.server = server
        self.ctx = server.context()
        self.port = port
        p = self.packet()
        p.open(port)
        # The following parameters were obtained from the MKS PDR2000 manual.
        p.baudrate(9600L)
        p.stopbits(1L)
        p.bytesize(8L)
        p.parity('N')
        p.timeout(0.1 * u.s)
        # Clear out the Rx buffer. This is necessary for some devices.
        yield p.send()
    
    def packet(self):
        '''Create a new packet in our private context'''
        return self.server.packet(context=self.ctx)

    def shutdown(self):
        '''Disconnect from teh serial port when we shut down.'''
        return self.packet().close().send()

    def rw_line(self, code):
        # Don't allow two concurrent read/write calls.
        
        self._lock = DeferredLock()

        return self._lock.run(partial(self._rw_line, code))

    @inlineCallbacks
    def _rw_line(self, code):
        '''Write data to the device.'''
        yield self.server.write_line(code, context=self.ctx)
        time.sleep(0.2)
        ans = yield self.server.read(context=self.ctx)
        returnValue(ans)
        
    @inlineCallbacks
    def getUnits(self):
        yield self.write_line('u')
        time.sleep(0.5)
        ans = yield self.read_line()
        returnValue(ans)
    def toFloat(self, val):
        try:
            if val == 'Off' or val == 'Low':
                return np.nan
            return float(val)
        except:
            return None
开发者ID:McDermott-Group,项目名称:servers,代码行数:58,代码来源:MKSPDR2000.py

示例2: VarianControllerWrapper

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import run [as 别名]
class VarianControllerWrapper(DeviceWrapper):
    @inlineCallbacks
    def connect(self, server, port):
        '''Connect the the guage controller'''
        print('Connecting to "%s" on port "%s"...' %(server.name, port))
        self.server = server
        self.ctx = server.context()
        self.port = port
        # The following parameters match the default configuration of 
        # the Varian unit.
        p = self.packet()
        p.open(port)
        p.baudrate(9600L)
        p.stopbits(1L)
        p.bytesize(8L)
        p.parity('N')
        p.rts(False)
        p.timeout(2 * units.s)
        # Clear out the read buffer. This is necessary for some devices.
        p.read_line()
        yield p.send()
        
    def packet(self):
        """Create a packet in our private context."""
        return self.server.packet(context=self.ctx)
    def shutdown(self):
        """Disconnect from the serial port when we shut down."""
        return self.packet().close().send()
        

    def rw_line(self, code):
        # Don't allow two concurrent read/write calls. Use deferred locking to
        # enforce this
        self._lock = DeferredLock()
        return self._lock.run(partial(self._rw_line, code))

    @inlineCallbacks
    def _rw_line(self, code):
        '''Write data to the device.'''
        yield self.server.write_line(code, context=self.ctx)
        time.sleep(0.1)
        ans = yield self.server.read(context=self.ctx)
        returnValue(ans)
开发者ID:McDermott-Group,项目名称:servers,代码行数:45,代码来源:Varian_XGS600.py

示例3: HendrixDeploy

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import run [as 别名]

#.........这里部分代码省略.........
            wsgi = importlib.import_module(wsgi_module)
        except ImportError:
            chalk.red("Unable to Import module '%s'\n" % wsgi_dot_path)
            raise
        return getattr(wsgi, application_name, None)

    @classmethod
    def getConf(cls, settings, options):
        "updates the options dict to use config options in the settings module"
        ports = ['http_port', 'https_port', 'cache_port']
        for port_name in ports:
            port = getattr(settings, port_name.upper(), None)
            # only use the settings ports if the defaults were left unchanged
            default = getattr(defaults, port_name.upper())
            if port and options.get(port_name) == default:
                options[port_name] = port

        _opts = [
            ('key', 'hx_private_key'),
            ('cert', 'hx_certficate'),
            ('wsgi', 'wsgi_application')
        ]
        for opt_name, settings_name in _opts:
            opt = getattr(settings, settings_name.upper(), None)
            if opt:
                options[opt_name] = opt

        if not options['settings']:
            options['settings'] = environ['DJANGO_SETTINGS_MODULE']
        return options

    def addServices(self):
        """
        a helper function used in HendrixDeploy.run
        it instanstiates the HendrixService and adds child services
        note that these services will also be run on all processes
        """
        self.addHendrix()

    def addGlobalServices(self):
        """
        This is where we put service that we don't want to be duplicated on
        worker subprocesses
        """
        pass

    def getThreadPool(self):
        '''
        Case to match twisted.internet.reactor
        '''
        return self.threadpool

    def addHendrix(self):
        '''
        Instantiates a HendrixService with this object's threadpool.
        It will be added as a service later.
        '''
        self.hendrix = HendrixService(
            self.application,
            threadpool=self.getThreadPool(),
            resources=self.resources,
            services=self.services,
            loud=self.options['loud']
        )
        if self.options["https_only"] is not True:
            self.hendrix.spawn_new_server(self.options['http_port'], HendrixTCPService)
开发者ID:hendrix,项目名称:hendrix,代码行数:70,代码来源:base.py

示例4: GPIBDeviceManager

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import run [as 别名]

#.........这里部分代码省略.........
        to the identification query.  If the response cannot be parsed
        or the query fails, the name will be listed as '<unknown>'.
        """
        for cls_cmd, idn_cmd in [('*CLS', '*IDN?'), ('', 'ID?'), ('CS', 'OI')]:
            resp = None
            name = UNKNOWN
            p = self.client.servers[server].packet()
            p.address(channel).timeout(Value(1,'s')).write(cls_cmd).query(idn_cmd)
            print("Sending '" + idn_cmd + "' to " + str(server) + " " + str(channel))
            try:
                resp = (yield p.send()).query
            except Exception:
                print("No response to '" + idn_cmd + "' from " + str(server) + " " + str(channel))
                continue
            name = parseIDNResponse(resp, idn_cmd)
            if name != UNKNOWN:
                print(str(server) + " " + str(channel) + " '" + idn_cmd + "' response: '" + resp + "'")
                print(str(server) + " " + str(channel) + " device name: '" + name + "'")
                break
        returnValue((name, resp))

    def identifyDevice(self, server, channel, idn):
        """Try to identify a new device with all ident functions.

        Returns the first name returned by a successful identification.
        """
        @inlineCallbacks
        def _doIdentifyDevice():
            for identifier in list(self.identFunctions.keys()):
                name = yield self.tryIdentFunc(server, channel, idn, identifier)
                if name is not None:
                    returnValue(name)
            returnValue(UNKNOWN)
        return self.identLock.run(_doIdentifyDevice)

    def identifyDevicesWithServer(self, identifier):
        """Try to identify all unknown devices with a new server."""
        @inlineCallbacks
        def _doServerIdentify():
            #yield self.client.refresh()
            for (server, channel), (device, idn) in list(self.knownDevices.items()):
                if device != UNKNOWN:
                    continue
                name = yield self.tryIdentFunc(server, channel, idn, identifier)
                if name is None:
                    continue
                self.knownDevices[server, channel] = (name, idn)
                if name in self.deviceServers:
                    self.notifyServers(name, server, channel, True)
        return self.identLock.run(_doServerIdentify)        

    @inlineCallbacks
    def tryIdentFunc(self, server, channel, idn, identifier):
        """Try calling one registered identification function.

        If the identification succeeds, returns the new name,
        otherwise returns None.
        """
        if identifier in self.identFunctions:
            s = self.client[identifier]
            setting, context = self.identFunctions[identifier]
            print("Trying to identify device " +  str(server) + " " + str(channel) + " on server " + str(identifier))
            try:
                if idn is None:
                    resp = yield s[setting](server, channel, context=context)
                else:
开发者ID:McDermott-Group,项目名称:LabRAD,代码行数:70,代码来源:gpib_device_manager.py

示例5: WorkQueue

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import run [as 别名]
class WorkQueue(object):
    """A WorkQueue contains WorkUnits and dispatches NonceRanges when requested
    by the miner. WorkQueues dispatch deffereds when they runs out of nonces.
    """

    def __init__(self, core):

        self.core = core
        self.logger = core.logger
        self.queueSize = core.config.get("general", "queuesize", int, 1)
        self.queueDelay = core.config.get("general", "queuedelay", int, 5)

        self.lock = DeferredLock()
        self.queue = deque("", self.queueSize)
        self.deferredQueue = deque()
        self.currentUnit = None
        self.lastBlock = None
        self.block = ""

        self.staleCallbacks = []

    def storeWork(self, aw):

        # check if this work matches the previous block
        if (self.lastBlock is not None) and (aw.identifier == self.lastBlock):
            self.logger.debug("Server gave work from the previous " "block, ignoring.")
            # if the queue is too short request more work
            if self.checkQueue():
                if self.core.connection:
                    self.core.connection.requestWork()
            return

        # create a WorkUnit
        work = WorkUnit(aw)
        reactor.callLater(max(60, aw.time - 1) - self.queueDelay, self.checkWork)
        reactor.callLater(max(60, aw.time - 1), self.workExpire, work)

        # check if there is a new block, if so reset queue
        newBlock = aw.identifier != self.block
        if newBlock:
            self.queue.clear()
            self.currentUnit = None
            self.lastBlock = self.block
            self.block = aw.identifier
            self.logger.debug("New block (WorkQueue)")

        # add new WorkUnit to queue
        if work.data and work.target and work.midstate and work.nonces:
            self.queue.append(work)

        # if the queue is too short request more work
        workRequested = False
        if self.checkQueue():
            if self.core.connection:
                self.core.connection.requestWork()
                workRequested = True

        # if there is a new block notify kernels that their work is now stale
        if newBlock:
            for callback in self.staleCallbacks:
                callback()
            self.staleCallbacks = []
        self.staleCallbacks.append(work.stale)

        # check if there are deferred WorkUnit requests pending
        # since requests to fetch a WorkUnit can add additional deferreds to
        # the queue, cache the size beforehand to avoid infinite loops.
        for i in range(len(self.deferredQueue)):
            df = self.deferredQueue.popleft()
            d = self.fetchUnit(workRequested)
            d.chainDeferred(df)

        # clear the idle flag since we just added work to queue
        self.core.reportIdle(False)

    def checkWork(self):
        # Called 5 seconds before any work expires in order to fetch more
        if self.checkQueue():
            if self.core.connection:
                self.core.requestWork()

    def checkQueue(self, added=False):

        # This function checks the queue length including the current unit
        size = 1

        # Check if the current unit will last long enough
        if self.currentUnit is None:
            if len(self.queue) == 0:
                return True
            else:
                size = 0
                if added:
                    rolls = self.queue[0].maxtime - self.queue[0].timestamp
                    # If new work can't be rolled, and queue would be too small
                    if rolls == 0 and (len(self.queue) - 1) < self.queueSize:
                        return True

        else:
            remaining = self.currentUnit.maxtime - self.currentUnit.timestamp
#.........这里部分代码省略.........
开发者ID:revcozmo,项目名称:phoenix,代码行数:103,代码来源:WorkQueue.py


注:本文中的twisted.internet.defer.DeferredLock.run方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。