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


Python threads.blockingCallFromThread函数代码示例

本文整理汇总了Python中twisted.internet.threads.blockingCallFromThread函数的典型用法代码示例。如果您正苦于以下问题:Python blockingCallFromThread函数的具体用法?Python blockingCallFromThread怎么用?Python blockingCallFromThread使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: __call__

    def __call__(self, environ, start_response):
        """
        This function have to be called in a worker thread, not the IO thread.
        """
        rargs = environ['wsgiorg.routing_args'][1]
        controller = rargs['controller']

        # Media Transport
        if controller == 'mt':
            name = rargs['name']
            if name in self.mts:
                return self.mts[name](environ, start_response)
            else:
                return not_found(environ, start_response)

        if controller != 'upnp':
            return not_found(environ, start_response)

        try:
            udn = rargs['udn']
            if isInIOThread():
                # TODO: read request body
                return self.devices[udn](environ, start_response)
            else:
                # read request body
                input = environ['wsgi.input']
                environ['upnp.body'] = input.read(self.SOAP_BODY_MAX)
                # call the app in IO thread
                args = [udn, environ, start_response]
                blockingCallFromThread(self.reactor, self._call_handler, args)
                return args[3]
        except Exception, e:
            #print e
            #print 'Unknown access: ' + environ['PATH_INFO']
            return not_found(environ, start_response)
开发者ID:provegard,项目名称:pyupnp,代码行数:35,代码来源:upnp.py

示例2: execute

 def execute(self, op):
     """
     @param op: operation to execute
     @return: None
     
     
     """
     self.fd = op.fd
     op.state = 'running'
     self.busy = True
     try:
         if (op.fd is None) and (op.name not in ('open', '_stop')):
             raise RuntimeError("Calling a file operation {0} on None".format(op.name))
         if op.name == '_stop':
             self.running = False
             result = True
         elif op.name == 'open':
             result = self.manager.take(open(*op.args, **op.kwargs))
             op.fd = result
         elif op.name == 'interaction':
             result = op.callable(op.fd.fd, *op.args, **op.kwargs)
         else:
             result = getattr(op.fd.fd, op.name)(*op.args, **op.kwargs)
         op.state = 'success'
         threads.blockingCallFromThread(self.manager.reactor, op.deferred.callback, result)
     except Exception as e:
         op.state = 'failure'
         threads.blockingCallFromThread(self.manager.reactor, op.deferred.errback, e)
     finally:
         self.busy = False
开发者ID:jafd,项目名称:txfileio,代码行数:30,代码来源:threaded.py

示例3: main

def main(iface):
    ret = 0
    try:
        a = AutoDHTServer()
        a.start(iface)

        b = AutoDHTServer()
        b.start(iface)

        time.sleep(4)

        print a.set(key="APA", value="banan")

        print a.get(key="APA")
        print b.get(key="APA")

        a.stop()
        b.stop()

    except:
        traceback.print_exc()
        ret = 1

    finally:
        if reactor.running:
            threads.blockingCallFromThread(reactor, reactor.stop)

    return ret
开发者ID:Tim-SHOOSAN,项目名称:calvin-base,代码行数:28,代码来源:dht_server.py

示例4: update

def update(event, bot):
	""" update will check for git update and restart bot if core files need updating. """

	gitpath = bot.getOption("git_path", module="pbm_updaterelaunch")
	if not gitpath:
		gitpath = "git"

	check_output([gitpath, "fetch"])
	changes = check_output([gitpath, "diff", "--name-status", "master", "origin/master"])
	print "CHANGES:", changes
	corechange = False
	modchange = False
	for line in changes.splitlines():
		if line.lstrip("M\t").startswith("modules/") or line.lstrip("A\t").startswith("modules/"):
			modchange = True
		elif line.endswith(".py"):
			corechange = True
	check_output([gitpath, "merge", "origin/master"])

	if corechange:
		print "RESTARTING BOT"
		#restart bot
		blockingCallFromThread(reactor, Settings.shutdown, True)

	elif modchange:
		#reload
		if bot.isModuleAvailable("pbm_reload"):
			bot.getModule("pbm_reload").admin_reload_bot(event, bot)
		else:
			bot.say("Module(s) updated but can't reload. reload module not available.")
	else:
		bot.say("Already up-to date.")
开发者ID:Clam-,项目名称:pyBurlyBot,代码行数:32,代码来源:pbm_updaterelaunch.py

示例5: syncRunServer

def syncRunServer(srv, host=C.MANAGER_HOST, port=None, username=None,
                  password=None, tls_mode=C.MANAGER_TLS):
    """Run a labrad server of the specified class in a synchronous context.

    Returns a context manager to be used with python's with statement that
    will yield when the server has started and then shut the server down after
    the context is exited.
    """
    from labrad import protocol

    tls_mode = C.check_tls_mode(tls_mode)

    if port is None:
        port = C.MANAGER_PORT_TLS if tls_mode == 'on' else C.MANAGER_PORT

    @inlineCallbacks
    def start_server():
        p = yield protocol.connect(host, port, tls_mode, username, password)
        yield srv.startup(p)

    @inlineCallbacks
    def stop_server():
        srv.disconnect()
        yield srv.onShutdown()

    thread.startReactor()
    blockingCallFromThread(reactor, start_server)
    try:
        yield
    finally:
        try:
            blockingCallFromThread(reactor, stop_server)
        except Exception:
            pass # don't care about exceptions here
开发者ID:labrad,项目名称:pylabrad,代码行数:34,代码来源:__init__.py

示例6: setOption

	def setOption(self, opt, value, channel=None, inreactor=False, **kwargs):
		if not self.event.isPM() and channel is None:
			if inreactor: self._botcont._settings.setOption(opt, value, channel=self.event.target, **kwargs)
			else: blockingCallFromThread(reactor, self._botcont._settings.setOption, opt, value, channel=self.event.target, **kwargs)
		else:
			if inreactor: self._botcont._settings.setOption(opt, value, channel=channel, **kwargs)
			else: blockingCallFromThread(reactor, self._botcont._settings.setOption, opt, value, channel=channel, **kwargs)
开发者ID:Clam-,项目名称:pyBurlyBot,代码行数:7,代码来源:wrapper.py

示例7: syncRunServer

def syncRunServer(srv, host=C.MANAGER_HOST, port=C.MANAGER_PORT, password=None):
    """Run a labrad server of the specified class in a synchronous context.

    Returns a context manager to be used with python's with statement that
    will yield when the server has started and then shut the server down after
    the context is exited.
    """

    if password is None:
        password = C.PASSWORD

    srv.password = password

    @inlineCallbacks
    def start_server():
        connector = reactor.connectTCP(host, port, srv)
        yield srv.onStartup()
        returnValue(connector)

    @inlineCallbacks
    def stop_server():
        yield srv.onShutdown()

    thread.startReactor()
    connector = blockingCallFromThread(reactor, start_server)
    try:
        yield
    finally:
        try:
            connector.disconnect()
            blockingCallFromThread(reactor, stop_server)
        except Exception:
            pass # don't care about exceptions here
开发者ID:z-michou,项目名称:pylabrad,代码行数:33,代码来源:__init__.py

示例8: __launch_blocker_thread

    def __launch_blocker_thread(self, user_id, user_name, x11_display, linuxsb):
        try:
            proclist = gtop.proclist(gtop.PROCLIST_KERN_PROC_UID, int(user_id))
            env_lang_var = "C"

            if len(proclist) > 0:
                for proc in proclist:
                    lang_var = (
                        Popen('cat /proc/%s/environ | tr "\\000" "\\n" | grep ^LANG= ' % proc, shell=True, stdout=PIPE)
                        .stdout.readline()
                        .strip("\n")
                    )
                    if len(lang_var) > 0:
                        env_lang_var = lang_var.replace("LANG=", "")
                        break

            cmd = ["su", user_name, "-c", "LANG=%s DISPLAY=%s nanny-desktop-blocker" % (env_lang_var, x11_display)]
            print cmd

            p = Popen(cmd)
            print "[LinuxSessionFiltering] launching blocker (pid : %s)" % p.pid

            while p.poll() == None:
                time.sleep(1)
                b = threads.blockingCallFromThread(reactor, linuxsb.is_user_blocked, user_id)
                if b == False:
                    p.terminate()
                    print "[LinuxSessionFiltering] Unblocking session %s" % user_id
                    return

            print "[LinuxSessionFiltering] blocker terminated by user interaction"
            threads.blockingCallFromThread(reactor, linuxsb.blocker_terminate_from_thread, user_id, p.poll())
        except:
            print "[LinuxSessionFiltering] blocker terminated by exception"
            threads.blockingCallFromThread(reactor, linuxsb.blocker_terminate_from_thread, user_id, 1)
开发者ID:tapia,项目名称:nanny,代码行数:35,代码来源:LinuxSessionFiltering.py

示例9: wrapBlocking

def wrapBlocking(f, *a, **kw):
    """This wraps a function to make sure all is halted until the function
    is done. This works also for functions that return deferreds."""
    try:
        threads.blockingCallFromThread(reactor, _wrapBlocking, f, *a, **kw)
    #        threads.blockingCallFromThread(reactor,f,*a,**kw)
    except:
        print "An exception was raised when wrapBlocking..."
开发者ID:spherecoder,项目名称:sphericalRepo,代码行数:8,代码来源:unity.py

示例10: open

 def open(self, path, flags):
   if threads.blockingCallFromThread(reactor, self.file_db.file_exists, self.key, path):
     file_path = os.path.join(self.file_dir, path[1:])
     if not self.file_is_up_to_date(file_path, path):
       # we need to find this file on the dht
       threads.blockingCallFromThread(reactor, self.file_service.download, path, file_path, self.key, True)
     
   return os.open(os.path.join(self.file_dir, path[1:]), flags)
开发者ID:darka,项目名称:p2pfs,代码行数:8,代码来源:file_system.py

示例11: flush

 def flush(self, path, fh):
   os.fsync(fh)
   if fh in self.updateables:
     full_file_path = os.path.join(self.file_dir, path[1:])
     mtime = threads.blockingCallFromThread(reactor, self.file_db.update_file_mtime, self.key, path)
     threads.blockingCallFromThread(reactor, self.file_db.update_size, self.key, path, os.path.getsize(full_file_path))
     reactor.callFromThread(self.file_service.publish_file, self.key, path, full_file_path, mtime)
     self.updateables.remove(fh)
   return 0
开发者ID:darka,项目名称:p2pfs,代码行数:9,代码来源:file_system.py

示例12: create

 def create(self, path, mode):
   threads.blockingCallFromThread(reactor, self.file_db.add_file, self.key, path, mode, 0)
   real_path = os.path.join(self.file_dir, path[1:])
   dir_path = os.path.dirname(real_path)
   if not os.path.exists(dir_path):
     self.log('create dir: {}'.format(dir_path))
     os.makedirs(dir_path)
   self.log('create file: {}'.format(real_path))
   return os.open(real_path, os.O_WRONLY | os.O_CREAT, mode)
开发者ID:darka,项目名称:p2pfs,代码行数:9,代码来源:file_system.py

示例13: teardown

def teardown(config, store):
    if reactor.running:
        tangelo.log_info("VTKWEB", "Shutting down Twisted reactor")
        threads.blockingCallFromThread(reactor, reactor.stop)

    if "processes" in store:
        tangelo.log_info("VTKWEB", "Terminating VTKWeb processes")
        for p in store["processes"].values():
            p["process"].terminate()
            p["process"].wait()
开发者ID:Kitware,项目名称:tangelo,代码行数:10,代码来源:control.py

示例14: run

 def run(self):
     sys.stderr.write("SshClientFactory running!\n")
     self.factory = SSHFactory(self)
     self.sem = Semaphore(0)
     def _connectLater():
         sys.stderr.write("SshClientFactory connecting asynchronously\n")
         reactor.connectTCP(self.host, self.port, self.factory)      #@UndefinedVariable
         sys.stderr.write("SshClientFactory connected\n")
     threads.blockingCallFromThread(reactor, _connectLater)          #@UndefinedVariable
     self.sem.acquire()
开发者ID:sys-git,项目名称:stb-rebooter,代码行数:10,代码来源:SshClient.py

示例15: testDataReceived

 def testDataReceived(self):
     self.assertNotEqual(self.protocol,None)
     threads.blockingCallFromThread(reactor,self.protocol.dataReceived,"This is a test line")
     threads.blockingCallFromThread(reactor,self.protocol.transport.loseConnection)
     unity.wait(0.1)
     f = open("testing.txt","r")
     self.assertNotEqual(f,None)
     l = f.readline()
     self.assertEqual(l,"This is a test line")
     f.close()
开发者ID:spherecoder,项目名称:sphericalRepo,代码行数:10,代码来源:TestFileReceiver.py


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