當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。