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


Python contextlib.suppress方法代码示例

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


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

示例1: _make_socket

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import suppress [as 别名]
def _make_socket(iface_name: str, can_fd: bool) -> socket.SocketType:
    s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
    try:
        s.bind((iface_name,))
        s.setsockopt(socket.SOL_SOCKET, _SO_TIMESTAMP, 1)  # timestamping
        if can_fd:
            s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FD_FRAMES, 1)

        s.setblocking(False)

        if 0 != s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR):
            raise OSError('Could not configure the socket: getsockopt(SOL_SOCKET, SO_ERROR) != 0')
    except BaseException:
        with contextlib.suppress(Exception):
            s.close()
        raise

    return s 
开发者ID:UAVCAN,项目名称:pyuavcan,代码行数:20,代码来源:_socketcan.py

示例2: test_reloader_live

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import suppress [as 别名]
def test_reloader_live(runargs, mode):
    with TemporaryDirectory() as tmpdir:
        filename = os.path.join(tmpdir, "reloader.py")
        text = write_app(filename, **runargs)
        proc = Popen(argv[mode], cwd=tmpdir, stdout=PIPE, creationflags=flags)
        try:
            timeout = Timer(5, terminate, [proc])
            timeout.start()
            # Python apparently keeps using the old source sometimes if
            # we don't sleep before rewrite (pycache timestamp problem?)
            sleep(1)
            line = scanner(proc)
            assert text in next(line)
            # Edit source code and try again
            text = write_app(filename, **runargs)
            assert text in next(line)
        finally:
            timeout.cancel()
            terminate(proc)
            with suppress(TimeoutExpired):
                proc.wait(timeout=3) 
开发者ID:huge-success,项目名称:sanic,代码行数:23,代码来源:test_reloader.py

示例3: render_voxel

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import suppress [as 别名]
def render_voxel(self, pred, thresh=0.4,
                     image_path=os.path.join(cfg.RENDERING.BLENDER_TMP_DIR, 'tmp.png')):
        # Cleanup the scene
        self.clearModel()
        out_f = os.path.join(cfg.RENDERING.BLENDER_TMP_DIR, 'tmp.obj')
        occupancy = pred > thresh
        vertices, faces = voxel2mesh(occupancy)
        with contextlib.suppress(IOError):
            os.remove(out_f)
        write_obj(out_f, vertices, faces)

        # Load the obj
        bpy.ops.import_scene.obj(filepath=out_f)
        bpy.context.scene.render.filepath = image_path
        bpy.ops.render.render(write_still=True)  # save straight to file

        im = np.array(Image.open(image_path))  # read the image

        # Last channel is the alpha channel (transparency)
        return im[:, :, :3], im[:, :, 3] 
开发者ID:chrischoy,项目名称:3D-R2N2,代码行数:22,代码来源:blender_renderer.py

示例4: _shutdown_on_exception

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import suppress [as 别名]
def _shutdown_on_exception(app: skein.ApplicationClient):
    # Ensure SIGINT is not masked to enable kill on C-c.
    import signal
    signal.signal(signal.SIGINT, signal.default_int_handler)

    try:
        yield
    except (KeyboardInterrupt, SystemExit):
        with suppress(SkeinError):
            app.shutdown(FinalStatus.KILLED)
        logger.error("Application killed on user request")
    except Exception:
        with suppress(SkeinError):
            app.shutdown(FinalStatus.FAILED)
        logger.exception("Application shutdown due to an exception")
        raise 
开发者ID:criteo,项目名称:tf-yarn,代码行数:18,代码来源:client.py

示例5: _aggregate_events

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import suppress [as 别名]
def _aggregate_events(
    kv: skein.kv.KeyValueStore,
    events: Dict[str, Dict[str, str]]
) -> None:
    """
    Aggregate events from all dispatched tasks.

    The lifecycle of a task consists of three stages:
    * init which carries the reserved socket address,
    * start with no payload, and
    * stop with an optional formatted exception.
    """
    # ``ConnectionError`` indicates that the app has finished and
    # the AM is down.
    queue = kv.events(event_type="PUT")
    with suppress(skein.exceptions.ConnectionError), queue:
        for evt in queue:
            if "/" in evt.key:
                task, stage = evt.key.rsplit("/", 1)
                events[task][stage] = evt.result.value.decode() 
开发者ID:criteo,项目名称:tf-yarn,代码行数:22,代码来源:client.py

示例6: events

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import suppress [as 别名]
def events(self, eventsockets):
        """used for external event loops: handle events that occur on one of the sockets of this server"""
        # we only react on events on our own server socket.
        # all other (client) sockets are owned by their individual threads.
        assert self.sock in eventsockets
        with contextlib.suppress(socket.timeout):   # just continue the loop on a timeout on accept
            events = self._selector.select(config.POLLTIMEOUT)
            if not events:
                return
            csock, caddr = self.sock.accept()
            if self.shutting_down:
                csock.close()
                return
            if hasattr(csock, "getpeercert"):
                log.debug("connected %s - SSL", caddr)
            else:
                log.debug("connected %s - unencrypted", caddr)
            if config.COMMTIMEOUT:
                csock.settimeout(config.COMMTIMEOUT)
            job = ClientConnectionJob(csock, caddr, self.daemon)
            try:
                self.pool.process(job)
            except NoFreeWorkersError:
                job.denyConnection("no free workers, increase server threadpool size") 
开发者ID:irmen,项目名称:Pyro5,代码行数:26,代码来源:svr_threads.py

示例7: close

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import suppress [as 别名]
def close(self):
        if self.housekeeper:
            self.housekeeper.stop.set()
            self.housekeeper.join()
            self.housekeeper = None
        if self.sock:
            with contextlib.suppress(socket.error, OSError):
                sockname = self.sock.getsockname()
            with contextlib.suppress(Exception):
                self.sock.close()
                if type(sockname) is str:
                    # it was a Unix domain socket, remove it from the filesystem
                    if os.path.exists(sockname):
                        os.remove(sockname)
            self.sock = None
        self.pool.close() 
开发者ID:irmen,项目名称:Pyro5,代码行数:18,代码来源:svr_threads.py

示例8: close

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import suppress [as 别名]
def close(self):
        if self.proxy and self.proxy._pyroConnection is not None:
            if self.pyroseq == self.proxy._pyroSeq:
                # we're still in sync, it's okay to use the same proxy to close this stream
                self.proxy._pyroInvoke("close_stream", [self.streamId], {},
                                       flags=protocol.FLAGS_ONEWAY, objectId=core.DAEMON_NAME)
            else:
                # The proxy's sequence number has diverged.
                # One of the reasons this can happen is because this call is being done from python's GC where
                # it decides to gc old iterator objects *during a new call on the proxy*.
                # If we use the same proxy and do a call in between, the other call on the proxy will get an out of sync seq and crash!
                # We create a temporary second proxy to call close_stream on. This is inefficient, but avoids the problem.
                with contextlib.suppress(errors.CommunicationError):
                    with self.proxy.__copy__() as closingProxy:
                        closingProxy._pyroInvoke("close_stream", [self.streamId], {},
                                                 flags=protocol.FLAGS_ONEWAY, objectId=core.DAEMON_NAME)
        self.proxy = None 
开发者ID:irmen,项目名称:Pyro5,代码行数:19,代码来源:client.py

示例9: bind_unused_port

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import suppress [as 别名]
def bind_unused_port(sock: socket.socket, host: Union[str, ipaddress.IPv4Address, ipaddress.IPv6Address] = 'localhost') -> int:
    """Bind the socket to a free port and return the port number.
    This code is based on the code in the stdlib's test.test_support module."""
    if sock.family in (socket.AF_INET, socket.AF_INET6) and sock.type == socket.SOCK_STREAM:
        if hasattr(socket, "SO_EXCLUSIVEADDRUSE"):
            with contextlib.suppress(socket.error):
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
    if not isinstance(host, str):
        host = str(host)
    if sock.family == socket.AF_INET:
        if host == 'localhost':
            sock.bind(('127.0.0.1', 0))
        else:
            sock.bind((host, 0))
    elif sock.family == socket.AF_INET6:
        if host == 'localhost':
            sock.bind(('::1', 0, 0, 0))
        else:
            sock.bind((host, 0, 0, 0))
    else:
        raise CommunicationError("unsupported socket family: " + str(sock.family))
    return sock.getsockname()[1] 
开发者ID:irmen,项目名称:Pyro5,代码行数:24,代码来源:socketutil.py

示例10: testCreateUnboundSockets6

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import suppress [as 别名]
def testCreateUnboundSockets6(self):
        if not has_ipv6:
            pytest.skip("no ipv6 capability")
        s = socketutil.create_socket(ipv6=True)
        assert socket.AF_INET6 == s.family
        bs = socketutil.create_bc_socket(ipv6=True)
        assert socket.AF_INET6 == bs.family
        with contextlib.suppress(socket.error):
            host, port, _, _ = s.getsockname()
            # can either fail with socket.error or return (host,0)
            assert 0 == port
        with contextlib.suppress(socket.error):
            host, port, _, _ = bs.getsockname()
            # can either fail with socket.error or return (host,0)
            assert 0 == port
        s.close()
        bs.close() 
开发者ID:irmen,项目名称:Pyro5,代码行数:19,代码来源:test_socketutil.py

示例11: _register_scatter

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import suppress [as 别名]
def _register_scatter():
    """
    Patch `PathCollection` and `scatter` to register their return values.

    This registration allows us to distinguish `PathCollection`s created by
    `Axes.scatter`, which should use point-like picking, from others, which
    should use path-like picking.  The former is more common, so we store the
    latter instead; this also lets us guess the type better if this module is
    imported late.
    """

    @functools.wraps(PathCollection.__init__)
    def __init__(self, *args, **kwargs):
        _nonscatter_pathcollections.add(self)
        return __init__.__wrapped__(self, *args, **kwargs)
    PathCollection.__init__ = __init__

    @functools.wraps(Axes.scatter)
    def scatter(*args, **kwargs):
        paths = scatter.__wrapped__(*args, **kwargs)
        with suppress(KeyError):
            _nonscatter_pathcollections.remove(paths)
        return paths
    Axes.scatter = scatter 
开发者ID:anntzer,项目名称:mplcursors,代码行数:26,代码来源:_pick_info.py

示例12: test_cancelled_error_not_captured

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import suppress [as 别名]
def test_cancelled_error_not_captured(
    sentry_init, aiohttp_client, loop, capture_events
):
    sentry_init(integrations=[AioHttpIntegration()])

    async def hello(request):
        raise asyncio.CancelledError()

    app = web.Application()
    app.router.add_get("/", hello)

    events = capture_events()
    client = await aiohttp_client(app)

    with suppress(ServerDisconnectedError):
        # Intended `aiohttp` interaction: server will disconnect if it
        # encounters `asyncio.CancelledError`
        await client.get("/")

    assert not events 
开发者ID:getsentry,项目名称:sentry-python,代码行数:22,代码来源:test_aiohttp.py

示例13: update

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import suppress [as 别名]
def update(self, data, properties):

        updated = self.set_property('location', properties['location'])
        updated |= self.set_property('creation_date', data.creation_date)
        updated |= self.set_property('bucket_policy', properties['bucket_policy'])
        updated |= self.set_property('website_enabled', properties['website_enabled'])
        updated |= self.set_property('metrics', properties['metrics'])

        with suppress(ClientError):
            tags = {t['Key']: t['Value'] for t in data.Tagging().tag_set}
            existing_tags = {x.key: x for x in self.tags}

            # Check for new tags
            for key, value in list(tags.items()):
                updated |= self.set_tag(key, value)

            # Check for updated or removed tags
            for key in list(existing_tags.keys()):
                if key not in tags:
                    updated |= self.delete_tag(key)

        return updated 
开发者ID:RiotGames,项目名称:cloud-inquisitor,代码行数:24,代码来源:resources.py

示例14: cls

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import suppress [as 别名]
def cls(self, target, source=None):
        if isinstance(target, str):
            target = resolve(target, package=self.target)
        if self.source and source is None:
            with suppress(ImportError):
                source_str = '{mod}.{cls}'.format(
                    mod=target.__module__.replace('.', self.module_sep),
                    cls=target.__name__)
                source = resolve(source_str, package=self.source)
            if not source:
                with suppress(AttributeError):
                    source = getattr(self.source, target.__name__)
        elif isinstance(source, str):
            source = resolve(source, package=self.source)
        if isinstance(target, type):
            return PatchClass(target, source)
        raise TypeError('Must be a valid class or class name') 
开发者ID:ashleywaite,项目名称:django-more,代码行数:19,代码来源:core.py

示例15: _join_daemon

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import suppress [as 别名]
def _join_daemon(self):
        with contextlib.suppress(IOError):
            os.waitpid(self.get_pid(), 0) 
开发者ID:cherrypy,项目名称:cherrypy,代码行数:5,代码来源:helper.py


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