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


Python contextlib.closing方法代码示例

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


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

示例1: test_copy_data_from

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import closing [as 别名]
def test_copy_data_from(self):
        try:
            tmpdir = tempfile.mkdtemp()

            # create new database
            with testing.postgresql.Postgresql(base_dir=tmpdir) as pgsql:
                conn = pg8000.connect(**pgsql.dsn())
                with closing(conn.cursor()) as cursor:
                    cursor.execute("CREATE TABLE hello(id int, value varchar(256))")
                    cursor.execute("INSERT INTO hello values(1, 'hello'), (2, 'ciao')")
                conn.commit()
                conn.close()

            # create another database from first one
            data_dir = os.path.join(tmpdir, 'data')
            with testing.postgresql.Postgresql(copy_data_from=data_dir) as pgsql:
                conn = pg8000.connect(**pgsql.dsn())
                with closing(conn.cursor()) as cursor:
                    cursor.execute('SELECT * FROM hello ORDER BY id')
                    self.assertEqual(cursor.fetchall(), ([1, 'hello'], [2, 'ciao']))
                conn.close()
        finally:
            rmtree(tmpdir) 
开发者ID:tk0miya,项目名称:testing.postgresql,代码行数:25,代码来源:test_postgresql.py

示例2: test_PostgresqlFactory_with_initialized_handler

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import closing [as 别名]
def test_PostgresqlFactory_with_initialized_handler(self):
        def handler(pgsql):
            conn = pg8000.connect(**pgsql.dsn())
            with closing(conn.cursor()) as cursor:
                cursor.execute("CREATE TABLE hello(id int, value varchar(256))")
                cursor.execute("INSERT INTO hello values(1, 'hello'), (2, 'ciao')")
            conn.commit()
            conn.close()

        Postgresql = testing.postgresql.PostgresqlFactory(cache_initialized_db=True,
                                                          on_initialized=handler)
        try:
            with Postgresql() as pgsql:
                conn = pg8000.connect(**pgsql.dsn())
                with closing(conn.cursor()) as cursor:
                    cursor.execute('SELECT * FROM hello ORDER BY id')
                    self.assertEqual(cursor.fetchall(), ([1, 'hello'], [2, 'ciao']))
                conn.close()
        finally:
            Postgresql.clear_cache() 
开发者ID:tk0miya,项目名称:testing.postgresql,代码行数:22,代码来源:test_postgresql.py

示例3: tcp_connection

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import closing [as 别名]
def tcp_connection(address):
    """Generator reading from tcp network transport layer"""
    logger = logging.getLogger('threaded.tcp-connection')
    logger.debug('... connecting to tcp://{}:{}'.format(*address))
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect(address)

    with closing(client_socket):
        while True:
            data = client_socket.recv(128)
            if data:
                logger.debug('<<< {!r}'.format(data))
                yield data
            else:
                logger.debug("... closed")
                break 
开发者ID:nokia,项目名称:moler,代码行数:18,代码来源:network_down_detector.py

示例4: list

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import closing [as 别名]
def list(uri):
  # Create instance of Engine 
  engine = Engine(uri)
  files = []
  # Ensure we'll close engine on exception 
  with closing(engine):
    # Start engine 
    engine.start()
    # Wait until files received 
    while not files and not xbmc.abortRequested:
        # Will list only video files in torrent
        files = engine.list(media_types=[MediaType.VIDEO])
        # Check if there is loading torrent error and raise exception 
        engine.check_torrent_error()
        xbmc.sleep(200)
  return files 
开发者ID:tdw1980,项目名称:tdw,代码行数:18,代码来源:tthp.py

示例5: get_max_range

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import closing [as 别名]
def get_max_range(baseurl):
    with closing(urlopen(baseurl + '/data/receiver.json', None, 5.0)) as f:
        receiver = json.load(f)

        if not (receiver.has_key('lat') and receiver.has_key('lon')):
            return None

        rlat = receiver['lat']
        rlon = receiver['lon']

        maxrange = None
        with closing(urlopen(baseurl + '/data/aircraft.json', None, 5.0)) as f:
            aircraft = json.load(f)
            for ac in aircraft['aircraft']:
                if ac.has_key('seen_pos') and ac['seen_pos'] < 300:
                    alat = ac['lat']
                    alon = ac['lon']
                    distance = greatcircle(rlat, rlon, alat, alon)
                    if maxrange is None or distance > maxrange:
                        maxrange = distance
                        
        return maxrange 
开发者ID:mutability,项目名称:dump1090-tools,代码行数:24,代码来源:fetch-dump1090-max-range.py

示例6: write

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import closing [as 别名]
def write(self, filename):
        with closing(open(filename + '.new', 'w')) as w:
            c = csv.writer(w)
            c.writerow(['bearing_start','bearing_end','bin_start','bin_end','samples','unique'])
            for b_low,b_high,histo in self.values():
                # make sure we write at least one value per sector,
                # it makes things a little easier when plotting
                first = True
                for h_low,h_high,count,unique in histo.values():
                    if unique or first:
                        c.writerow(['%f' % b_low,
                                    '%f' % b_high,
                                    '%f' % h_low,
                                    '%f' % h_high,
                                    '%d' % count,
                                    '%d' % unique])
                        first = False
        os.rename(filename + '.new', filename) 
开发者ID:mutability,项目名称:dump1090-tools,代码行数:20,代码来源:adsb-polar.py

示例7: read

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import closing [as 别名]
def read(self, filename):
        with closing(open(filename, 'r')) as r:
            csvfile = csv.reader(r)
            csvfile.next() # skip header
            for row in csvfile:
                b_low = float(row[0])
                b_high = float(row[1])
                h_low = float(row[2])
                h_high = float(row[3])                

                if len(row) > 5:
                    count = int(row[4])
                    unique = int(row[5])
                else:
                    # older format with only count/unique stored
                    count = int( float(row[4]) * 10.0 )
                    unique = 10

                self.import_sector(b_low, b_high, h_low, h_high, count, unique) 
开发者ID:mutability,项目名称:dump1090-tools,代码行数:21,代码来源:adsb-polar.py

示例8: test_max_clients

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import closing [as 别名]
def test_max_clients(self):
        AsyncHTTPClient.configure(SimpleAsyncHTTPClient)
        with closing(AsyncHTTPClient(
                self.io_loop, force_instance=True)) as client:
            self.assertEqual(client.max_clients, 10)
        with closing(AsyncHTTPClient(
                self.io_loop, max_clients=11, force_instance=True)) as client:
            self.assertEqual(client.max_clients, 11)

        # Now configure max_clients statically and try overriding it
        # with each way max_clients can be passed
        AsyncHTTPClient.configure(SimpleAsyncHTTPClient, max_clients=12)
        with closing(AsyncHTTPClient(
                self.io_loop, force_instance=True)) as client:
            self.assertEqual(client.max_clients, 12)
        with closing(AsyncHTTPClient(
                self.io_loop, max_clients=13, force_instance=True)) as client:
            self.assertEqual(client.max_clients, 13)
        with closing(AsyncHTTPClient(
                self.io_loop, max_clients=14, force_instance=True)) as client:
            self.assertEqual(client.max_clients, 14) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:23,代码来源:simple_httpclient_test.py

示例9: test_multi_line_headers

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import closing [as 别名]
def test_multi_line_headers(self):
        # Multi-line http headers are rare but rfc-allowed
        # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
        sock, port = bind_unused_port()
        with closing(sock):
            def write_response(stream, request_data):
                if b"HTTP/1." not in request_data:
                    self.skipTest("requires HTTP/1.x")
                stream.write(b"""\
HTTP/1.1 200 OK
X-XSS-Protection: 1;
\tmode=block

""".replace(b"\n", b"\r\n"), callback=stream.close)

            def accept_callback(conn, address):
                stream = IOStream(conn, io_loop=self.io_loop)
                stream.read_until(b"\r\n\r\n",
                                  functools.partial(write_response, stream))
            netutil.add_accept_handler(sock, accept_callback, self.io_loop)
            self.http_client.fetch("http://127.0.0.1:%d/" % port, self.stop)
            resp = self.wait()
            resp.rethrow()
            self.assertEqual(resp.headers['X-XSS-Protection'], "1; mode=block")
            self.io_loop.remove_handler(sock.fileno()) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:27,代码来源:httpclient_test.py

示例10: test_add_callback_while_closing

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import closing [as 别名]
def test_add_callback_while_closing(self):
        # Issue #635: add_callback() should raise a clean exception
        # if called while another thread is closing the IOLoop.
        closing = threading.Event()

        def target():
            other_ioloop.add_callback(other_ioloop.stop)
            other_ioloop.start()
            closing.set()
            other_ioloop.close(all_fds=True)
        other_ioloop = IOLoop()
        thread = threading.Thread(target=target)
        thread.start()
        closing.wait()
        for i in range(1000):
            try:
                other_ioloop.add_callback(lambda: None)
            except RuntimeError as e:
                self.assertEqual("IOLoop is closing", str(e))
                break 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:22,代码来源:ioloop_test.py

示例11: test_handler_callback_file_object

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import closing [as 别名]
def test_handler_callback_file_object(self):
        """The handler callback receives the same fd object it passed in."""
        server_sock, port = bind_unused_port()
        fds = []

        def handle_connection(fd, events):
            fds.append(fd)
            conn, addr = server_sock.accept()
            conn.close()
            self.stop()
        self.io_loop.add_handler(server_sock, handle_connection, IOLoop.READ)
        with contextlib.closing(socket.socket()) as client_sock:
            client_sock.connect(('127.0.0.1', port))
            self.wait()
        self.io_loop.remove_handler(server_sock)
        self.io_loop.add_handler(server_sock.fileno(), handle_connection,
                                 IOLoop.READ)
        with contextlib.closing(socket.socket()) as client_sock:
            client_sock.connect(('127.0.0.1', port))
            self.wait()
        self.assertIs(fds[0], server_sock)
        self.assertEqual(fds[1], server_sock.fileno())
        self.io_loop.remove_handler(server_sock.fileno())
        server_sock.close() 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:26,代码来源:ioloop_test.py

示例12: open

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import closing [as 别名]
def open(self, mode: QIODevice.OpenMode) -> contextlib.closing:
        """Open the underlying device and ensure opening succeeded.

        Raises OSError if opening failed.

        Args:
            mode: QIODevice::OpenMode flags.

        Return:
            A contextlib.closing() object so this can be used as
            contextmanager.
        """
        ok = self.dev.open(mode)
        if not ok:
            raise QtOSError(self.dev)
        return contextlib.closing(self) 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:18,代码来源:qtutils.py

示例13: process_module

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import closing [as 别名]
def process_module(self, node):
        """Process the module."""
        if os.path.basename(os.path.splitext(node.file)[0]) == '__init__':
            return
        max_lineno = 1
        with contextlib.closing(node.stream()) as stream:
            for (lineno, line) in enumerate(stream):
                if lineno == 1 and line.startswith(b'#!'):
                    max_lineno += 1
                    continue
                elif line.startswith(b'# vim:'):
                    if lineno > max_lineno:
                        self.add_message('modeline-position', line=lineno)
                    if (line.rstrip() != b'# vim: ft=python '
                                         b'fileencoding=utf-8 sts=4 sw=4 et:'):
                        self.add_message('invalid-modeline', line=lineno)
                    break
            else:
                self.add_message('modeline-missing', line=1) 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:21,代码来源:modeline.py

示例14: _add_device

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import closing [as 别名]
def _add_device(self, device):
        if self._check_port:
            # check that the device port is opened
            with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
                sock.settimeout(_DEFAULT_TIMEOUT)
                try:
                    res = sock.connect_ex((device.ip_addr, device.port))
                except (socket.error, OSError):
                    self.logger.debug("{} is unreachable".format(device.ip_addr))
                    return
                if res != 0:
                    self.logger.debug("{}:{} is closed".format(device.ip_addr, device.port))
                    return
        # add this device to the "discovered" devices
        f = self._thread_loop.run_async(self._do_add_device, device)
        try:
            f.result_or_cancel(timeout=_DEFAULT_TIMEOUT)
        except concurrent.futures.TimeoutError:
            self.logger.error("raw discovery timedout for {}:{}".format(
                device.ip_addr, device.port)) 
开发者ID:Parrot-Developers,项目名称:olympe,代码行数:22,代码来源:discovery.py

示例15: ExtractName

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import closing [as 别名]
def ExtractName(font_or_file, name_id, default):
  """Extracts a name table field (first value if many) from a font.

  Args:
    font_or_file: path to a font file or a TTFont.
    name_id: the ID of the name desired. Use NAME_* constant.
    default: result if no value is present.
  Returns:
    The value of the first entry for name_id or default if there isn't one.
  """
  value = default
  names = []
  if isinstance(font_or_file, ttLib.TTFont):
    names = ExtractNames(font_or_file, name_id)
  else:
    with contextlib.closing(ttLib.TTFont(font_or_file)) as font:
      names = ExtractNames(font, name_id)

  if names:
    value = names[0]

  return value 
开发者ID:googlefonts,项目名称:gftools,代码行数:24,代码来源:google_fonts.py


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