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


Python sys.exc_clear函数代码示例

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


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

示例1: UnRegisterObjectChangeHandler

 def UnRegisterObjectChangeHandler(self, callback):
     try:
         del self.objectChangeHandlers[callback]
     except ReferenceError as e:
         sys.exc_clear()
     except KeyError as e:
         sys.exc_clear()
开发者ID:Pluckyduck,项目名称:eve,代码行数:7,代码来源:ObjectCallGPCS.py

示例2: nb_write

    def nb_write(fd, buf):
        """
        Write some number of bytes from buffer *buf* to file
        descriptor *fd*. Return the number of bytes written, which may
        be less than the length of *buf*.

        The file descriptor must be in non-blocking mode.
        """
        hub = None
        event = None
        try:
            while 1:
                try:
                    result = _write(fd, buf)
                    return result
                except OSError as e:
                    if e.errno not in ignored_errors:
                        raise
                    if not PY3:
                        sys.exc_clear()
                if hub is None:
                    hub = get_hub()
                    event = hub.loop.io(fd, 2)
                hub.wait(event)
        finally:
            if event is not None:
                event.close()
                event = None
                hub = None
开发者ID:gevent,项目名称:gevent,代码行数:29,代码来源:os.py

示例3: send

 def send(self, data, flags=0, timeout=timeout_default):
     sock = self._sock
     if timeout is timeout_default:
         timeout = self.timeout
     try:
         return sock.send(data, flags)
     except error:
         ex = sys.exc_info()[1]
         if ex.args[0] != EWOULDBLOCK or timeout == 0.0:
             raise
         sys.exc_clear()
         try:
             self._wait(self._write_event)
         except error:
             ex = sys.exc_info()[1]
             if ex.args[0] == EBADF:
                 return 0
             raise
         try:
             return sock.send(data, flags)
         except error:
             ex2 = sys.exc_info()[1]
             if ex2.args[0] == EWOULDBLOCK:
                 return 0
             raise
开发者ID:awestendorf,项目名称:gevent,代码行数:25,代码来源:socket.py

示例4: _job_store_checker

    def _job_store_checker(self):
        while not self._stopped:
            LOG.debug(
                "Starting Scheduler Job Store checker [scheduler=%s]...", self
            )

            try:
                self._process_store_jobs()
            except Exception:
                LOG.exception(
                    "Scheduler failed to process delayed calls"
                    " due to unexpected exception."
                )

                # For some mysterious reason (probably eventlet related)
                # the exception is not cleared from the context automatically.
                # This results in subsequent log.warning calls to show invalid
                # info.
                if sys.version_info < (3,):
                    sys.exc_clear()

            eventlet.sleep(
                self._fixed_delay +
                random.Random().randint(0, self._random_delay * 1000) * 0.001
            )
开发者ID:openstack,项目名称:mistral,代码行数:25,代码来源:default_scheduler.py

示例5: __iowait

 def __iowait(self, io_func, *args, **kwargs):
     timeout = self._sock.gettimeout() or 0.1
     fd = self._sock.fileno()
     time_start = time.time()
     while True:
         try:
             return io_func(*args, **kwargs)
         except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantX509LookupError):
             sys.exc_clear()
             _, _, errors = select.select([fd], [], [fd], timeout)
             if errors:
                 raise
             time_now = time.time()
             if time_now - time_start > timeout:
                 break
         except OpenSSL.SSL.WantWriteError:
             sys.exc_clear()
             _, _, errors = select.select([], [fd], [fd], timeout)
             if errors:
                 raise
             time_now = time.time()
             if time_now - time_start > timeout:
                 break
         except Exception as e:
             #xlog.exception("e:%r", e)
             raise e
开发者ID:Mattgenius,项目名称:XX-Net,代码行数:26,代码来源:openssl_wrap.py

示例6: _writePhase

  def _writePhase(self, args):
    # defaults
    q = {
       'fname' : 'phase.xml',
      'sensor' : 'MSI',
       'bands' : '1, 2, 3, 4, 5, 6, 7, 8, 9, 10'
    }
    for a in args:
      q[a] = args[a]
    pdata = '''
<?xml version="1.0" encoding="UTF-8"?>
<DartFile version="5.4.3">
    <Phase expertMode="0">
        <DartInputParameters calculatorMethod="0">
            <nodefluxtracking gaussSiedelAcceleratingTechnique="1" numberOfIteration="4"/>
            <SpectralDomainTir temperatureMode="0">
                <Atmosphere_1 SKYLForTemperatureAssignation="0.0"/>
            </SpectralDomainTir>
            <SpectralIntervals>
                <SpectralIntervalsProperties bandNumber="0"
                    deltaLambda="0.005493" meanLambda="0.56925"
                    radiativeBudgetProducts="0" spectralDartMode="0"/>
            </SpectralIntervals>
            <ExpertModeZone albedoThreshold="1.0E-5"
                illuminationRepartitionMode="2"
                lightPropagationThreshold="1.0E-4"
                nbRandomPointsPerInteceptionAtmosphere="10"
                nbSubSubcenterTurbidEmission="40"
                nbSubcenterIllumination="10" nbSubcenterVolume="2"/>
            <nodeIlluminationMode illuminationMode="0" irradianceMode="1">
                <irradianceDatabaseNode irradianceDatabase="TOASolarIrradiance.txt"/>
            </nodeIlluminationMode>
        </DartInputParameters>
        <DartProduct>
            <dartModuleProducts allIterationsProducts="0"
                brfProducts="1" lidarProducts="0"
                order1Products="0" radiativeBudgetProducts="0">
                <BrfProductsProperties brfProduct="1" extrapolation="1"
                    horizontalOversampling="1" image="1"
                    luminanceProducts="1" maximalThetaImages="0.1"
                    nb_scene="1" outputHapkeFile="0" projection="1"
                    sensorOversampling="1" sensorPlaneprojection="0">
                    <ExpertModeZone_Etalement etalement="2"/>
                    <ExpertModeZone_maskProjection mask_projection="0"/>
                </BrfProductsProperties>
            </dartModuleProducts>
            <maketModuleProducts MNEProducts="0" areaMaketProducts="0"
                coverRateProducts="0" laiProducts="0"/>
        </DartProduct>
    </Phase>
</DartFile>
'''[1:-1] % ()
    try:
      VLAB.copyfile(q['fname'], '%s_%s' % (q['fname'], time.time()))
    except Exception:
      if not sys.platform.startswith('java'):
        sys.exc_clear()
    fp = open(q['fname'], 'w')
    fp.write(pdata)
    fp.close()
开发者ID:anarisris,项目名称:esa-beam,代码行数:60,代码来源:dart.py

示例7: close

    def close(self, reason = None):
        try:
            self.socket.close()
        except socket.error as e:
            sys.exc_clear()

        self.socket = None
开发者ID:Pluckyduck,项目名称:eve,代码行数:7,代码来源:SocketGPS.py

示例8: Reprocess

    def Reprocess(self, items, activeShipID):
        fromLocation = self._GetFromLocationID(items)
        itemIDs = []
        try:
            for item in items:
                itemID = item.itemID
                self._CheckIsRefiningShip(activeShipID, itemID)
                if not self._IsInSameLocation(fromLocation, item):
                    continue
                self._LockItem(item, itemIDs)

            try:
                if len(itemIDs):
                    ownerID, flag = session.charid, invconst.flagHangar
                    skipChecks = []
                    while True:
                        try:
                            self._DoReprocess(itemIDs, ownerID, fromLocation, flag, skipChecks)
                        except UserError as e:
                            sys.exc_clear()
                            if self.AskToContinue(e):
                                skipChecks.append(e.msg)
                                continue

                        break

            except:
                sys.exc_clear()

        finally:
            self._UnlockItems(itemIDs)
开发者ID:connoryang,项目名称:dec-eve-serenity,代码行数:31,代码来源:itemReprocessor.py

示例9: _actual_start

def _actual_start():
  """Another layer in the starting stack."""
  # Get raw traceback
  tb = None
  try:
    raise ZeroDivisionError('')
  except ZeroDivisionError:
    tb = sys.exc_info()[2]
  assert tb

  # Look at previous stack frame's previous stack frame (previous
  # frame is run() or start(); the frame before that should be the
  # frame of the original caller, which should be __main__ or appcommands
  prev_prev_frame = tb.tb_frame.f_back.f_back
  if not prev_prev_frame:
    return
  prev_prev_name = prev_prev_frame.f_globals.get('__name__', None)
  if (prev_prev_name != '__main__'
      and not prev_prev_name.endswith('.appcommands')):
    return
  # just in case there's non-trivial stuff happening in __main__
  del tb
  sys.exc_clear()

  try:
    really_start()
  except SystemExit, e:
    raise
开发者ID:Dean-Christian-Armada,项目名称:django,代码行数:28,代码来源:app.py

示例10: run

	def run(self):
		self.logger.info("Starting Snort alert processor main thread...")
		
		try:
			os.setuid(int(self.options.uid))
		except OSError:
			self.logger.error("Could not change user for Snort alert processor")
			return
		
		try:
			os.remove(self.options.unsock)
		except OSError:
			pass
		
		self.queue_processor.start()
		
		self.logger.debug("Binding UNIX socket for Snort alerts at " + self.options.unsock)
		
		try:
			self.server = SnortAlertServer(self.logger, self.options.unsock, SnortAlertHandler)
			self.server.serve_forever()
		except:
			self.logger.error("Could not start Snort processor (detailed log message follows):")
			self.logger.error(sys.exc_info())
			sys.exc_clear()
			self.stop()
开发者ID:justindthomas,项目名称:flower_as,代码行数:26,代码来源:snort.py

示例11: NameValueListToDict

def NameValueListToDict(name_value_list):
  """
  Takes an array of strings of the form 'NAME=VALUE' and creates a dictionary
  of the pairs. If a string is simply NAME, then the value in the dictionary
  is set to True. If VALUE can be converted to a boolean or integer, it is.
  """
  result = {}
  for item in name_value_list:
    tokens = item.split('=', 1)
    if len(tokens) == 2:
      token_value = tokens[1]
      if token_value.lower() == 'true':
        token_value = True
      elif token_value.lower() == 'false':
        token_value = False
      else:
        # If we can make it an int, use that, otherwise, use the string.
        try:
          token_value = int(token_value)
        except ValueError:
          sys.exc_clear()
      # Set the variable to the supplied value.
      result[tokens[0]] = token_value
    else:
      # No value supplied, treat it as a boolean and set it.
      result[tokens[0]] = True
  return result
开发者ID:NexMirror,项目名称:cef,代码行数:27,代码来源:gn_args.py

示例12: send

 def send(self,raw_data,retry_timeout=1):
     """ Writes raw outgoing data. Blocks until done.
         If supplied data is unicode string, encodes it to utf-8 before send."""
     if type(raw_data)==type(u''): raw_data = raw_data.encode('utf-8')
     elif type(raw_data)<>type(''): raw_data = ustr(raw_data).encode('utf-8')
     try:
         sent = 0
         while not sent:
             try:
                 self._send(raw_data)
                 sent = 1
             except socket.sslerror, e:
                 if e[0]==socket.SSL_ERROR_WANT_READ:
                     sys.exc_clear()
                     self.DEBUG("SSL_WANT_READ while sending data, wating to retry",'warn')
                     select.select([self._sock],[],[],retry_timeout)
                     continue
                 if e[0]==socket.SSL_ERROR_WANT_WRITE:
                     sys.exc_clear()
                     self.DEBUG("SSL_WANT_WRITE while sending data, waiting to retry",'warn')
                     select.select([],[self._sock],[],retry_timeout)
                     continue
                 raise
         # Avoid printing messages that are empty keepalive packets.
         if raw_data.strip():
             self.DEBUG(raw_data,'sent')
             if hasattr(self._owner, 'Dispatcher'): # HTTPPROXYsocket will send data before we have a Dispatcher
                 self._owner.Dispatcher.Event('', DATA_SENT, raw_data)
开发者ID:gebner,项目名称:xmpppy,代码行数:28,代码来源:transports.py

示例13: testMemoryIsFreed

  def testMemoryIsFreed(self):
    # Note: we use `set` values for components and metadata because we need
    # to construct weakrefs to them.  Other builtin types, such as `list` and
    # `tuple`, do not support weakrefs.
    ct1 = CT(set([1, 2]), set(['no', 'leaks']))
    ct2 = CT(set([3, 4]), set(['no', 'leaks']))
    ct3 = CT(set([5, 6]), set(['other', 'metadata']))

    # Note: map_structure exercises flatten, pack_sequence_as, and
    # assert_same_structure.
    func = lambda x, y: x | y
    ct4 = nest.map_structure(func, ct1, ct2, expand_composites=True)

    # Check that the exception-raising path in assert_same_structure
    # doesn't leak any objects.
    with self.assertRaisesRegexp(ValueError,
                                 ".*don't have the same nested structure.*"):
      nest.map_structure(func, ct2, ct3, expand_composites=True)
    if hasattr(sys, 'exc_clear'):
      sys.exc_clear()  # Remove any references in exception stack traces.

    refs = []
    for ct in [ct1, ct2, ct3, ct4]:
      refs.append(weakref.ref(ct))
      refs.append(weakref.ref(ct.components))
      refs.append(weakref.ref(ct.metadata))
    del ct  # pylint: disable=undefined-loop-variable

    for ref in refs:
      self.assertIsNotNone(ref())

    del ct1, ct2, ct3, ct4
    gc.collect()
    for ref in refs:
      self.assertIsNone(ref())
开发者ID:aritratony,项目名称:tensorflow,代码行数:35,代码来源:composite_tensor_test.py

示例14: _chunk_read

def _chunk_read(response, chunk_size=32768, report_hook=None, filename=None):
    file_data = []
    if response.info().has_key('Content-Length'):
        total_size = response.info().getheader('Content-Length').strip()
        total_size = int(total_size)
    else:
        # No size
        total_size = None
        if report_hook:
            print '* Warning: No total file size available.'
    if (filename == None) and (response.info().has_key('Content-Disposition')):
        # If the response has Content-Disposition, we take file name from it
        try:
            filename = response.info()['Content-Disposition'].split('filename=')[1]
            if filename[0] == '"' or filename[0] == "'":
                filename = filename[1:-1]
        except Exception:
            sys.exc_clear()
            filename = 'output'
    if (filename == None):
        if report_hook:
            print "* No detected filename, using 'output'"
        filename = 'output'
    bytes_so_far = 0
    while True:
        chunk = response.read(chunk_size)
        bytes_so_far += len(chunk)
        if not chunk:
            break
        else:
            file_data.append(chunk)
        report_hook(bytes_so_far, chunk_size, total_size)
    return (file_data, filename)
开发者ID:briarfox,项目名称:shellista-pipista,代码行数:33,代码来源:pipista_plugin.py

示例15: _request

    def _request(self, url, data=None, referrer='http://google.com/', ajax=False):
        handlers = [self.cookie_handler]
        if self.proxy:
            handlers.append(self.proxy)
        opener = urllib.request.build_opener(*handlers)
        self._add_headers(opener, referrer, ajax)

        html = ''
        try:
            req = urllib.request.Request(url, data)
            res = opener.open(req, timeout=30)
            html = res.read()
        except Exception as e:
            print("Something went terribly wrong {e}".format(e=e))
            return False, {}, {}

        headers = res.info()
        if ('Content-Encoding' in list(headers.keys()) and headers['Content-Encoding'] == 'gzip') or \
                ('content-encoding' in list(headers.keys()) and headers['content-encoding'] == 'gzip'):
            data = io.BytesIO(html)
            gzipper = gzip.GzipFile(fileobj=data)
            try:
                html_unzipped = gzipper.read()
            except Exception:
                sys.exc_clear()
            else:
                html = html_unzipped

        cookies = {cookie.name: cookie.value for cookie in self.cookie_jar}
        self.csrf_token = cookies['csrftoken']

        return html, headers, cookies
开发者ID:mahoutm,项目名称:pinterest-pinata,代码行数:32,代码来源:client_py3.py


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