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


Python cStringIO.close方法代码示例

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


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

示例1: __str__

# 需要导入模块: from six.moves import cStringIO [as 别名]
# 或者: from six.moves.cStringIO import close [as 别名]
    def __str__(self):
        buffer = StringIO()

        if self.refTime is not None:
            refTimeInSecs = self.refTime.getTime() / 1000
            micros = (self.refTime.getTime() % 1000) * 1000
            dtObj = datetime.datetime.utcfromtimestamp(refTimeInSecs)
            dtObj = dtObj.replace(microsecond=micros)
            # This won't be compatible with java or string from java since its to microsecond
            buffer.write(dtObj.isoformat(' '))

        if "FCST_USED" in self.utilityFlags:
            hrs = int(self.fcstTime / 3600)
            mins = int((self.fcstTime - (hrs * 3600)) / 60)
            buffer.write(" (" + str(hrs))
            if mins != 0:
                buffer.write(":" + str(mins))
            buffer.write(")")

        if "PERIOD_USED" in self.utilityFlags:
            buffer.write("[")
            buffer.write(self.validPeriod.start.isoformat(' '))
            buffer.write("--")
            buffer.write(self.validPeriod.end.isoformat(' '))
            buffer.write("]")

        strVal = buffer.getvalue()
        buffer.close()
        return strVal
开发者ID:mjames-upc,项目名称:python-awips,代码行数:31,代码来源:DataTime.py

示例2: _decompress_xz

# 需要导入模块: from six.moves import cStringIO [as 别名]
# 或者: from six.moves.cStringIO import close [as 别名]
            def _decompress_xz(filename):
                """Eumlates an option function in read mode for xz.

                See the comment in _compress_xz for more information.

                This function tries to emulate the lzma module as much as
                possible

                """
                if not filename.endswith('.xz'):
                    filename = '{}.xz'.format(filename)

                try:
                    with open(os.devnull, 'w') as null:
                        string = subprocess.check_output(
                            ['xz', '--decompress', '--stdout', filename],
                            stderr=null)
                except OSError as e:
                    if e.errno == errno.ENOENT:
                        raise exceptions.PiglitFatalError(
                            'No xz binary available')
                    raise

                # We need a file-like object, so the contents must be placed in
                # a StringIO object.
                io = StringIO()
                io.write(string)
                io.seek(0)

                yield io

                io.close()
开发者ID:BNieuwenhuizen,项目名称:piglit,代码行数:34,代码来源:compression.py

示例3: IncludedResponse

# 需要导入模块: from six.moves import cStringIO [as 别名]
# 或者: from six.moves.cStringIO import close [as 别名]
class IncludedResponse(object):

    def __init__(self):
        self.headers = None
        self.status = None
        self.output = StringIO()
        self.str = None

    def close(self):
        self.str = self.output.getvalue()
        self.output.close()
        self.output = None

    def write(self, s):
        assert self.output is not None, (
            "This response has already been closed and no further data "
            "can be written.")
        self.output.write(s)

    def __str__(self):
        return self.body

    def body__get(self):
        if self.str is None:
            return self.output.getvalue()
        else:
            return self.str
    body = property(body__get)
开发者ID:10sr,项目名称:hue,代码行数:30,代码来源:recursive.py

示例4: test_for_mapping_long_doc_in_write_conf

# 需要导入模块: from six.moves import cStringIO [as 别名]
# 或者: from six.moves.cStringIO import close [as 别名]
    def test_for_mapping_long_doc_in_write_conf(self):
        n = self._some_namespaces()
        n = Namespace(doc='top')
        n.add_option(
            'aaa',
            'Default Value Goes In Here',
            'This time the documentation string is really long. So long '
            'that we have to write it on multiple lines.',
        )
        cm = ConfigurationManager(
            n,
            values_source_list=[],
        )
        out = StringIO()
        cm.write_conf(for_mapping, opener=stringIO_context_wrapper(out))
        received = out.getvalue()
        out.close()
        for line in received.splitlines():
            self.assertTrue(len(line) < 80, line)
        expected = """
# This time the documentation string is really long. So long that we have to
# write it on multiple lines. (default: 'Default Value Goes In Here')
aaa='Default Value Goes In Here'
        """.strip()
        if six.PY3:
            expected = expected.replace("='", "=b'")
        self.assertEqual(received.strip(), expected)
开发者ID:mozilla,项目名称:configman,代码行数:29,代码来源:test_val_for_mapping.py

示例5: test_write_ini_with_custom_converters

# 需要导入模块: from six.moves import cStringIO [as 别名]
# 或者: from six.moves.cStringIO import close [as 别名]
        def test_write_ini_with_custom_converters(self):

            def dict_encoder(dict_):
                return ','.join('%s:%s' % (k, v) for (k, v) in dict_.items())

            def dict_decoder(string):
                return dict(x.split(':') for x in string.split(','))

            n = Namespace(doc='top')
            n.add_option(
                'a',
                default={'one': 'One'},
                doc='the doc string',
                to_string_converter=dict_encoder,
                from_string_converter=dict_decoder,
            )
            c = ConfigurationManager(
                [n],
                use_admin_controls=True,
                use_auto_help=False,
                argv_source=[]
            )
            expected = "# the doc string\n#a=one:One\n"
            out = StringIO()
            c.write_conf(for_configobj, opener=stringIO_context_wrapper(out))
            received = out.getvalue()
            out.close()

            self.assertEqual(expected.strip(), received.strip())
开发者ID:mozilla,项目名称:configman,代码行数:31,代码来源:test_val_for_configobj.py

示例6: scan

# 需要导入模块: from six.moves import cStringIO [as 别名]
# 或者: from six.moves.cStringIO import close [as 别名]
def scan(path):
    """
    Performs an in-process binary module scan. That means the module is
    loaded (imported) into the current Python interpreter.
    
        "path" - a path to a binary module to scan
    
    Returns a CIX 2.0 XML string.
    """
    
    from gencix.python import gencixcore as gencix
    
    name,_ = os.path.splitext(os.path.basename(path))
    dir = os.path.dirname(path)

    root = gencix.Element('codeintel', version='2.0', name=name)
    
    gencix.docmodule(name, root, usefile=True, dir=dir)
    gencix.perform_smart_analysis(root)
    gencix.prettify(root)
    
    tree = gencix.ElementTree(root)
    
    stream = StringIO()
    try:
        stream.write('<?xml version="1.0" encoding="UTF-8"?>\n')
        tree.write(stream)
        return stream.getvalue()
    finally:
        stream.close()
开发者ID:SublimeCodeIntel,项目名称:codeintel,代码行数:32,代码来源:pybinary.py

示例7: test_write_json

# 需要导入模块: from six.moves import cStringIO [as 别名]
# 或者: from six.moves.cStringIO import close [as 别名]
    def test_write_json(self):
        n = Namespace(doc='top')
        n.add_option(
            'aaa',
            '2011-05-04T15:10:00',
            'the a',
            short_form='a',
            from_string_converter=datetime_from_ISO_string
        )

        c = ConfigurationManager(
            [n],
            use_admin_controls=True,
            use_auto_help=False,
            argv_source=[]
        )

        out = StringIO()
        c.write_conf(for_json, opener=stringIO_context_wrapper(out))
        received = out.getvalue()
        out.close()
        jrec = json.loads(received)

        expect_to_find = {
            "short_form": "a",
            "default": "2011-05-04T15:10:00",
            "doc": "the a",
            "value": "2011-05-04T15:10:00",
            "from_string_converter":
            "configman.datetime_util.datetime_from_ISO_string",
            "name": "aaa"
        }
        for key, value in expect_to_find.items():
            self.assertEqual(jrec['aaa'][key], value)
开发者ID:mozilla,项目名称:configman,代码行数:36,代码来源:test_val_for_json.py

示例8: picture_view

# 需要导入模块: from six.moves import cStringIO [as 别名]
# 或者: from six.moves.cStringIO import close [as 别名]
def picture_view(request, user_id, year=None):
    """Displays a view of a user's picture.

    Args:
        user_id
            The ID of the user whose picture is being fetched.
        year
            The user's picture from this year is fetched. If not
            specified, use the preferred picture.
    """
    try:
        user = User.get_user(id=user_id)
    except User.DoesNotExist:
        raise Http404
    default_image_path = os.path.join(settings.PROJECT_ROOT, "static/img/default_profile_pic.png")

    if user is None:
        raise Http404
    else:
        if year is None:
            preferred = user.preferred_photo
            if preferred is not None:
                if preferred.endswith("Photo"):
                    preferred = preferred[:-len("Photo")]

            if preferred == "AUTO":
                data = user.default_photo()
                if data is None:
                    image_buffer = io.open(default_image_path, mode="rb")
                else:
                    image_buffer = StringIO(data)

            # Exclude 'graduate' from names array
            elif preferred in Grade.names:
                data = user.photo_binary(preferred)

                if data:
                    image_buffer = StringIO(data)
                else:
                    image_buffer = io.open(default_image_path, mode="rb")
            else:
                image_buffer = io.open(default_image_path, mode="rb")
        else:
            data = user.photo_binary(year)
            if data:
                image_buffer = StringIO(data)
            else:
                image_buffer = io.open(default_image_path, mode="rb")

        response = HttpResponse(content_type="image/jpeg")
        response["Content-Disposition"] = "filename={}_{}.jpg".format(user_id, year or preferred)
        try:
            img = image_buffer.read()
        except UnicodeDecodeError:
            img = io.open(default_image_path, mode="rb").read()

        image_buffer.close()
        response.write(img)

        return response
开发者ID:willzhang05,项目名称:ion,代码行数:62,代码来源:views.py

示例9: run_pylint

# 需要导入模块: from six.moves import cStringIO [as 别名]
# 或者: from six.moves.cStringIO import close [as 别名]
def run_pylint():
    buff = StringIO()
    reporter = text.ParseableTextReporter(output=buff)
    args = ["-rn", "--disable=all", "--enable=" + enabled_codes ,"murano"]
    lint.Run(args, reporter=reporter, exit=False)
    val = buff.getvalue()
    buff.close()
    return val
开发者ID:aawm,项目名称:murano,代码行数:10,代码来源:lintstack.py

示例10: run_pylint

# 需要导入模块: from six.moves import cStringIO [as 别名]
# 或者: from six.moves.cStringIO import close [as 别名]
def run_pylint():
    buff = StringIO()
    reporter = text.ParseableTextReporter(output=buff)
    args = ["--include-ids=y", "-E", "sahara"]
    lint.Run(args, reporter=reporter, exit=False)
    val = buff.getvalue()
    buff.close()
    return val
开发者ID:Chinmoy-Dey,项目名称:sahara,代码行数:10,代码来源:lintstack.py

示例11: run_pylint

# 需要导入模块: from six.moves import cStringIO [as 别名]
# 或者: from six.moves.cStringIO import close [as 别名]
def run_pylint():
    buff = StringIO()
    args = ["--msg-template={path}:{line}: [{msg_id}({symbol}), {obj}] {msg}",
            "-E",
            "ceilometer"]
    lint.Run(args, exit=False)
    val = buff.getvalue()
    buff.close()
    return val
开发者ID:AVerma87,项目名称:ceilometer,代码行数:11,代码来源:lintstack.py

示例12: run_pylint

# 需要导入模块: from six.moves import cStringIO [as 别名]
# 或者: from six.moves.cStringIO import close [as 别名]
def run_pylint():
    buff = StringIO()
    reporter = text.TextReporter(output=buff)
    args = [
        "--msg-template='{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}'",
        "-E", "cinderclient"]
    lint.Run(args, reporter=reporter, exit=False)
    val = buff.getvalue()
    buff.close()
    return val
开发者ID:openstack,项目名称:python-cinderclient,代码行数:12,代码来源:lintstack.py

示例13: get_cix_string

# 需要导入模块: from six.moves import cStringIO [as 别名]
# 或者: from six.moves.cStringIO import close [as 别名]
def get_cix_string(cix, prettyFormat=True):
    # Get the CIX.
    if prettyFormat:
        prettify(cix)
    cixstream = StringIO()
    cixtree = ElementTree(cix)
    cixstream.write('<?xml version="1.0" encoding="UTF-8"?>\n')
    cixtree.write(cixstream)
    cixcontent = cixstream.getvalue()
    cixstream.close()
    return cixcontent
开发者ID:SublimeCodeIntel,项目名称:codeintel,代码行数:13,代码来源:gencix_utils.py

示例14: _format_stack

# 需要导入模块: from six.moves import cStringIO [as 别名]
# 或者: from six.moves.cStringIO import close [as 别名]
def _format_stack(frame):
    """
    Pretty-print the stack of `frame` like logging would.
    """
    sio = StringIO()
    sio.write("Stack (most recent call last):\n")
    traceback.print_stack(frame, file=sio)
    sinfo = sio.getvalue()
    if sinfo[-1] == "\n":
        sinfo = sinfo[:-1]
    sio.close()
    return sinfo
开发者ID:hynek,项目名称:structlog,代码行数:14,代码来源:_frames.py

示例15: _format_exception

# 需要导入模块: from six.moves import cStringIO [as 别名]
# 或者: from six.moves.cStringIO import close [as 别名]
def _format_exception(exc_info):
    """
    Prettyprint an `exc_info` tuple.

    Shamelessly stolen from stdlib's logging module.
    """
    sio = StringIO()
    traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], None, sio)
    s = sio.getvalue()
    sio.close()
    if s[-1:] == "\n":
        s = s[:-1]
    return s
开发者ID:hynek,项目名称:structlog,代码行数:15,代码来源:_frames.py


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