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


Python StringIO.close方法代码示例

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


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

示例1: get_correct_indentation_diff

# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
def get_correct_indentation_diff(code, filename):
    """
    Generate a diff to make code correctly indented.

    :param code: a string containing a file's worth of Python code
    :param filename: the filename being considered (used in diff generation only)
    :returns: a unified diff to make code correctly indented, or
              None if code is already correctedly indented
    """
    code_buffer = StringIO(code)
    output_buffer = StringIO()
    reindenter = reindent.Reindenter(code_buffer)
    reindenter.run()
    reindenter.write(output_buffer)
    reindent_output = output_buffer.getvalue()
    output_buffer.close()
    if code != reindent_output:
        diff_generator = difflib.unified_diff(code.splitlines(True), reindent_output.splitlines(True),
                                              fromfile=filename, tofile=filename + " (reindented)")
        # work around http://bugs.python.org/issue2142
        diff_tuple = map(clean_diff_line_for_python_bug_2142, diff_generator)
        diff = "".join(diff_tuple)
        return diff
    else:
        return None
开发者ID:ChienliMa,项目名称:Theano,代码行数:27,代码来源:check_whitespace.py

示例2: test_roundtrip_sequence_collections_and_alignments

# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
    def test_roundtrip_sequence_collections_and_alignments(self):
        fps = list(map(lambda e: list(map(get_data_path, e)),
                       [('empty', 'empty'),
                        ('fasta_sequence_collection_different_type',
                         'qual_sequence_collection_different_type')]))

        for reader, writer in ((_fasta_to_sequence_collection,
                                _sequence_collection_to_fasta),
                               (_fasta_to_alignment,
                                _alignment_to_fasta)):
            for fasta_fp, qual_fp in fps:
                # read
                obj1 = reader(fasta_fp, qual=qual_fp)

                # write
                fasta_fh = StringIO()
                qual_fh = StringIO()
                writer(obj1, fasta_fh, qual=qual_fh)
                fasta_fh.seek(0)
                qual_fh.seek(0)

                # read
                obj2 = reader(fasta_fh, qual=qual_fh)
                fasta_fh.close()
                qual_fh.close()

                # TODO remove this custom equality testing code when
                # SequenceCollection has an equals method (part of #656).
                # We need this method to include IDs and description in the
                # comparison (not part of SequenceCollection.__eq__).
                self.assertEqual(obj1, obj2)
                for s1, s2 in zip(obj1, obj2):
                    self.assertTrue(s1.equals(s2))
开发者ID:sh4wn,项目名称:scikit-bio,代码行数:35,代码来源:test_fasta.py

示例3: _in_process_execute

# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
    def _in_process_execute(self, cli_ctx, command, expect_failure=False):
        from six import StringIO
        from vcr.errors import CannotOverwriteExistingCassetteException

        if command.startswith('az '):
            command = command[3:]

        stdout_buf = StringIO()
        logging_buf = StringIO()
        try:
            # issue: stderr cannot be redirect in this form, as a result some failure information
            # is lost when command fails.
            self.exit_code = cli_ctx.invoke(shlex.split(command), out_file=stdout_buf) or 0
            self.output = stdout_buf.getvalue()
            self.applog = logging_buf.getvalue()

        except CannotOverwriteExistingCassetteException as ex:
            raise AssertionError(ex)
        except CliExecutionError as ex:
            if expect_failure:
                self.exit_code = 1
                self.output = stdout_buf.getvalue()
                self.applog = logging_buf.getvalue()
            elif ex.exception:
                raise ex.exception
            else:
                raise ex
        except Exception as ex:  # pylint: disable=broad-except
            self.exit_code = 1
            self.output = stdout_buf.getvalue()
            self.process_error = ex
        finally:
            stdout_buf.close()
            logging_buf.close()
开发者ID:derekbekoe,项目名称:azure-cli,代码行数:36,代码来源:base.py

示例4: fetch_data

# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
    def fetch_data(self):
        # create a data frame directly from the full text of
        # the response from the returned file-descriptor.
        data = self.fetch_url(self.url)
        fd = StringIO()

        if isinstance(data, str):
            fd.write(data)
        else:
            for chunk in data:
                fd.write(chunk)

        self.fetch_size = fd.tell()

        fd.seek(0)

        try:
            # see if pandas can parse csv data
            frames = read_csv(fd, **self.pandas_kwargs)

            frames_hash = hashlib.md5(str(fd.getvalue()).encode('utf-8'))
            self.fetch_hash = frames_hash.hexdigest()
        except pd.parser.CParserError:
            # could not parse the data, raise exception
            raise Exception('Error parsing remote CSV data.')
        finally:
            fd.close()

        return frames
开发者ID:barrygolden,项目名称:zipline,代码行数:31,代码来源:requests_csv.py

示例5: test_roundtrip_biological_sequences

# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
    def test_roundtrip_biological_sequences(self):
        fps = list(map(lambda e: list(map(get_data_path, e)),
                       [('fasta_multi_seq_roundtrip',
                         'qual_multi_seq_roundtrip'),
                        ('fasta_sequence_collection_different_type',
                         'qual_sequence_collection_different_type')]))

        for reader, writer in ((_fasta_to_biological_sequence,
                                _biological_sequence_to_fasta),
                               (partial(_fasta_to_dna_sequence,
                                        validate=False),
                                _dna_sequence_to_fasta),
                               (partial(_fasta_to_rna_sequence,
                                        validate=False),
                                _rna_sequence_to_fasta),
                               (partial(_fasta_to_protein_sequence,
                                        validate=False),
                                _protein_sequence_to_fasta)):
            for fasta_fp, qual_fp in fps:
                # read
                obj1 = reader(fasta_fp, qual=qual_fp)

                # write
                fasta_fh = StringIO()
                qual_fh = StringIO()
                writer(obj1, fasta_fh, qual=qual_fh)
                fasta_fh.seek(0)
                qual_fh.seek(0)

                # read
                obj2 = reader(fasta_fh, qual=qual_fh)
                fasta_fh.close()
                qual_fh.close()

                self.assertEqual(obj1, obj2)
开发者ID:johnchase,项目名称:scikit-bio,代码行数:37,代码来源:test_fasta.py

示例6: test_roundtrip_sequence_collections_and_alignments

# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
    def test_roundtrip_sequence_collections_and_alignments(self):
        fps = list(map(lambda e: list(map(get_data_path, e)),
                       [('empty', 'empty'),
                        ('fasta_sequence_collection_different_type',
                         'qual_sequence_collection_different_type')]))

        for reader, writer in ((_fasta_to_sequence_collection,
                                _sequence_collection_to_fasta),
                               (_fasta_to_alignment,
                                _alignment_to_fasta)):
            for fasta_fp, qual_fp in fps:
                # read
                obj1 = reader(fasta_fp, qual=qual_fp)

                # write
                fasta_fh = StringIO()
                qual_fh = StringIO()
                writer(obj1, fasta_fh, qual=qual_fh)
                fasta_fh.seek(0)
                qual_fh.seek(0)

                # read
                obj2 = reader(fasta_fh, qual=qual_fh)
                fasta_fh.close()
                qual_fh.close()

                self.assertEqual(obj1, obj2)
开发者ID:johnchase,项目名称:scikit-bio,代码行数:29,代码来源:test_fasta.py

示例7: __call__

# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
 def __call__(self, parser, namespace, values, option_string=None):
     output = StringIO()
     parser.print_help(output)
     text = output.getvalue()
     output.close()
     pydoc.pager(text)
     parser.exit()
开发者ID:catkin,项目名称:xylem,代码行数:9,代码来源:arguments.py

示例8: write_to_db

# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
 def write_to_db(self, db, transaction=None, commit=True):
     if transaction is None:
         transaction = db
     fp = StringIO()
     if len(self) < Timeseries.MAX_ALL_BOTTOM:
         top = ''
         middle = None
         self.write(fp)
         bottom = fp.getvalue()
     else:
         dates = sorted(self.keys())
         self.write(fp, end=dates[Timeseries.ROWS_IN_TOP_BOTTOM - 1])
         top = fp.getvalue()
         fp.truncate(0)
         fp.seek(0)
         self.write(fp, start=dates[Timeseries.ROWS_IN_TOP_BOTTOM],
                    end=dates[-(Timeseries.ROWS_IN_TOP_BOTTOM + 1)])
         middle = self.blob_create(
             zlib.compress(fp.getvalue().encode('ascii')))
         fp.truncate(0)
         fp.seek(0)
         self.write(fp, start=dates[-Timeseries.ROWS_IN_TOP_BOTTOM])
         bottom = fp.getvalue()
     fp.close()
     c = db.cursor()
     c.execute("DELETE FROM ts_records WHERE id=%d" % (self.id))
     c.execute("""INSERT INTO ts_records (id, top, middle, bottom)
                  VALUES (%s, %s, %s, %s)""", (self.id, top, middle,
               bottom))
     c.close()
     if commit:
         transaction.commit()
开发者ID:aptiko,项目名称:pthelma,代码行数:34,代码来源:timeseries.py

示例9: _save_data

# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
    def _save_data(self, key, hmmfile, stofile, colnames, x, cur=None):
        with open(hmmfile) as fh:
            hmmdata = fh.read()

        with open(stofile) as fh:
            stodata = fh.read()

        phylo = True if x.dtype == float else False

        coldata = json.dumps(colnames)
        xfile = StringIO()
        np.save(xfile, x)
        xdata = bz2.compress(xfile.getvalue(), 9)
        xfile.close()

        closable = False
        if cur is None:
            conn = sqlite3.connect(self.__filename)
            cur = conn.cursor()
            closable = True

        IdepiProjectData.__insert(cur, IdepiProjectData.__HMM, key, hmmdata)
        IdepiProjectData.__insert(cur, IdepiProjectData.__ALIGNMENT, key, stodata)
        IdepiProjectData.__insert(cur, IdepiProjectData.__COLUMNS, key, coldata)
        if phylo:
            IdepiProjectData.__insert(cur, IdepiProjectData.__PHYLO_DATA, key, xdata)
        else:
            IdepiProjectData.__insert(cur, IdepiProjectData.__DISCRETE_DATA, key, xdata)

        if closable:
            conn.close()
开发者ID:erikvolz,项目名称:idepi-ev0,代码行数:33,代码来源:_idepiprojectdata.py

示例10: open

# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
 def open(self, filename=None):
     if filename is None:
         filename = self._base_uri
     else:
         if self._file_type == 's3':
             filename = urljoin(self._base_uri.replace(
                 's3://', 'http://'), filename.replace('\\', '/')).replace('http://', 's3://')
         elif self._file_type == 'http':
             filename = urljoin(self._base_uri, filename.replace('\\', '/'))
         else:
             filename = os.path.abspath(os.path.join(os.path.dirname(
                 self._base_uri.replace('\\', '/')), filename.replace('\\', '/')))
     f = None
     if self._file_type == 's3':
         uri_header, uri_body = filename.split('://', 1)
         us = uri_body.split('/')
         bucketname = us.pop(0)
         key = '/'.join(us)
         logger.info('Opening {}'.format(key))
         f = StringIO(self._s3_bucket.Object(key).get()['Body'].read())
     elif self._file_type == 'http':
         f = request.urlopen(filename)
     else:
         f = open(filename, 'rb')
     yield f
     f.close()
开发者ID:zwsong,项目名称:nnabla,代码行数:28,代码来源:data_source_loader.py

示例11: _log_metadata

# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
    def _log_metadata(self, project):
        dependencies = self._extract_dependencies(project)

        output = StringIO()
        writer = csv.DictWriter(output, delimiter=',',
                                quoting=csv.QUOTE_MINIMAL,
                                lineterminator="\n",
                                fieldnames=ordered_fieldnames)

        for dep in dependencies:
            license, homepage = self._get_pypi_license_homepage(**dep)

            if homepage and 'launchpad.net' in homepage:
                license = self._get_launchpad_license(homepage)

            if license == "UNKNOWN":
                license = ""

            if homepage == "UNKNOWN":
                homepage = ""

            info = dep
            info['license_info'] = license
            info['homepage'] = homepage
            info['project_name'] = project.name
            writer.writerow(info)

        self._project_deps[project.name] = output.getvalue()
        output.close()
开发者ID:blueboxgroup,项目名称:giftwrap-plugins,代码行数:31,代码来源:package_meta.py

示例12: test_config_yaml_with_env

# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
def test_config_yaml_with_env():
    #assert False, "Not Implemented"
    fileobj = StringIO(CONFIG)
    result = config_from_yaml(fileobj=fileobj, silent=True, upper_only=False, parse_env=True)
    fileobj.close()
    print(result)
    assert result['postfix']['home'] == HOME_ENV    
开发者ID:srault95,项目名称:tplconfig,代码行数:9,代码来源:test_yaml.py

示例13: test_roundtrip_biological_sequences

# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
    def test_roundtrip_biological_sequences(self):
        fps = map(get_data_path, ['fasta_multi_seq_roundtrip',
                                  'fasta_sequence_collection_different_type'])

        for reader, writer in ((_fasta_to_biological_sequence,
                                _biological_sequence_to_fasta),
                               (_fasta_to_nucleotide_sequence,
                                _nucleotide_sequence_to_fasta),
                               (_fasta_to_dna_sequence,
                                _dna_sequence_to_fasta),
                               (_fasta_to_rna_sequence,
                                _rna_sequence_to_fasta),
                               (_fasta_to_protein_sequence,
                                _protein_sequence_to_fasta)):
            for fp in fps:
                # read
                obj1 = reader(fp)

                # write
                fh = StringIO()
                writer(obj1, fh)
                fh.seek(0)

                # read
                obj2 = reader(fh)
                fh.close()

                self.assertTrue(obj1.equals(obj2))
开发者ID:nathanxma,项目名称:scikit-bio,代码行数:30,代码来源:test_fasta.py

示例14: make_word

# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
    def make_word(self, seed=None, min=3, max=30, tries=100):
        if seed is not None or not self._seeded:
            self._random.seed(seed)

        out = StringIO()
        tail = CircularBuffer(self.tail)
        tail.append(WORD_START)

        while True:
            c = self.choose_transition(self.transitions(tail.tuple()), self._random.random())

            if c == WORD_STOP:
                break
            else:
                out.write(c)
                tail.append(c)

        result = out.getvalue()
        out.close()

        if min <= len(result) <= max:
            return result
        elif tries > 0:
            return self.make_word(seed, min, max, tries - 1)
        else:
            raise MatrixError
开发者ID:Xowap,项目名称:gibi,代码行数:28,代码来源:matrix.py

示例15: _in_process_execute

# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
    def _in_process_execute(self, command):
        # from azure.cli import  as cli_main
        from azure.cli.main import main as cli_main
        from six import StringIO
        from vcr.errors import CannotOverwriteExistingCassetteException

        if command.startswith('az '):
            command = command[3:]

        output_buffer = StringIO()
        try:
            # issue: stderr cannot be redirect in this form, as a result some failure information
            # is lost when command fails.
            self.exit_code = cli_main(shlex.split(command), file=output_buffer) or 0
            self.output = output_buffer.getvalue()
        except CannotOverwriteExistingCassetteException as ex:
            raise AssertionError(ex)
        except CliExecutionError as ex:
            if ex.exception:
                raise ex.exception
            else:
                raise ex
        except Exception as ex:  # pylint: disable=broad-except
            self.exit_code = 1
            self.output = output_buffer.getvalue()
            self.process_error = ex
        finally:
            output_buffer.close()
开发者ID:Visual-Studio-China,项目名称:azure-cli-int,代码行数:30,代码来源:base.py


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