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


Python StringIO.StringIO方法代码示例

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


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

示例1: add_log_stream

# 需要导入模块: import StringIO [as 别名]
# 或者: from StringIO import StringIO [as 别名]
def add_log_stream(self, stream=sys.stderr, level=logging.INFO):
		"""
		Add a stream where messages are outputted to.

		@param stream: stderr/stdout or a file stream
		@type stream: file | FileIO | StringIO
		@param level: minimum level of messages to be logged
		@type level: int | long

		@return: None
		@rtype: None
		"""
		assert self.is_stream(stream)
		# assert isinstance(stream, (file, io.FileIO))
		assert level in self._levelNames

		err_handler = logging.StreamHandler(stream)
		err_handler.setFormatter(self.message_formatter)
		err_handler.setLevel(level)
		self._logger.addHandler(err_handler) 
开发者ID:CAMI-challenge,项目名称:CAMISIM,代码行数:22,代码来源:loggingwrapper.py

示例2: __init__

# 需要导入模块: import StringIO [as 别名]
# 或者: from StringIO import StringIO [as 别名]
def __init__(self, separator="\t", logfile=None, verbose=True):
		"""
			Handle tab separated files

			@attention:

			@param separator: default character assumed to separate values in a file
			@type separator: str | unicode
			@param logfile: file handler or file path to a log file
			@type logfile: file | io.FileIO | StringIO.StringIO | basestring
			@param verbose: Not verbose means that only warnings and errors will be past to stream
			@type verbose: bool

			@return: None
			@rtype: None
		"""
		assert logfile is None or isinstance(logfile, basestring) or self.is_stream(logfile)
		assert isinstance(separator, basestring), "separator must be string"
		assert isinstance(verbose, bool), "verbose must be true or false"
		super(MetadataTable, self).__init__(label="MetadataReader", logfile=logfile, verbose=verbose)

		self._number_of_rows = 0
		self._meta_table = {}
		self._separator = separator
		self._list_of_column_names = [] 
开发者ID:CAMI-challenge,项目名称:CAMISIM,代码行数:27,代码来源:metadatatable.py

示例3: get_data_from_biodbnet

# 需要导入模块: import StringIO [as 别名]
# 或者: from StringIO import StringIO [as 别名]
def get_data_from_biodbnet(self, df_hgnc):
        """keys are unique Gene names
        
        input is made of the df based on HGNC data web services

        uniprot accession are duplicated sometimes. If som this is actually the
        iprimary accession entry and all secondary ones.


        e.g. ,
        
        ABHD11 >>>> Q8N723;Q8NFV2;Q8NFV3;Q6PJU0;Q8NFV4;H7BYM8;Q8N722;Q9HBS8 ABHDB_HUMAN Alpha/beta hydrolase domain-containing protein 11
        correspond actually to the primary one : Q8NFV4

        """
        b = biodbnet.BioDBNet()
        res2 = b.db2db("Gene Symbol", ["HGNC ID", "UniProt Accession", "UniProt Entry Name", "UniProt Protein Name", "KEGG Gene ID", "Ensembl Gene ID"], 
                res.keys()[0:2000])

        import pandas as pd
        import StringIO
        c = pd.read_csv(StringIO.StringIO(res2), delimiter="\t", index_col="Gene Symbol")
        return c 
开发者ID:cokelaer,项目名称:bioservices,代码行数:25,代码来源:mappers.py

示例4: dummy_open

# 需要导入模块: import StringIO [as 别名]
# 或者: from StringIO import StringIO [as 别名]
def dummy_open(x, mode="r"):
  if mode == "r":
    known = {
      "/sw/BUILD/27ce49698e818e8efb56b6eff6dd785e503df341/defaults-release/.build_succeeded": (0, StringIO("0")),
      "/sw/BUILD/3e90b4e08bad439fa5f25282480d1adb9efb0c0d/zlib/.build_succeeded": (0, StringIO("0")),
      "/sw/BUILD/%s/ROOT/.build_succeeded" % TEST_ROOT_BUILD_HASH: (0, StringIO("0")),
      "/sw/osx_x86-64/defaults-release/v1-1/.build-hash": (1, StringIO("27ce49698e818e8efb56b6eff6dd785e503df341")),
      "/sw/osx_x86-64/zlib/v1.2.3-1/.build-hash": (1, StringIO("3e90b4e08bad439fa5f25282480d1adb9efb0c0d")),
      "/sw/osx_x86-64/ROOT/v6-08-30-1/.build-hash": (1, StringIO(TEST_ROOT_BUILD_HASH))
    }
    if not x in known:
      return DEFAULT
    threshold, result = known[x]
    if threshold > TIMES_ASKED.get(x, 0):
      result = None
    TIMES_ASKED[x] = TIMES_ASKED.get(x, 0) + 1
    if not result:
      raise IOError
    return result
  return StringIO() 
开发者ID:alisw,项目名称:alibuild,代码行数:22,代码来源:test_build.py

示例5: _copy_eclipse_settings

# 需要导入模块: import StringIO [as 别名]
# 或者: from StringIO import StringIO [as 别名]
def _copy_eclipse_settings(p, files=None):
    processors = p.annotation_processors()

    settingsDir = join(p.dir, ".settings")
    mx.ensure_dir_exists(settingsDir)

    for name, sources in p.eclipse_settings_sources().items():
        out = StringIO()
        print('# GENERATED -- DO NOT EDIT', file=out)
        for source in sources:
            print('# Source:', source, file=out)
            with open(source) as f:
                print(f.read(), file=out)
        if p.javaCompliance:
            jc = p.javaCompliance if p.javaCompliance.value < _max_Eclipse_JavaExecutionEnvironment else mx.JavaCompliance(_max_Eclipse_JavaExecutionEnvironment)
            content = out.getvalue().replace('${javaCompliance}', str(jc))
        else:
            content = out.getvalue()
        if processors:
            content = content.replace('org.eclipse.jdt.core.compiler.processAnnotations=disabled', 'org.eclipse.jdt.core.compiler.processAnnotations=enabled')
        mx.update_file(join(settingsDir, name), content)
        if files:
            files.append(join(settingsDir, name)) 
开发者ID:graalvm,项目名称:mx,代码行数:25,代码来源:mx_ide_eclipse.py

示例6: get_shell_commands

# 需要导入模块: import StringIO [as 别名]
# 或者: from StringIO import StringIO [as 别名]
def get_shell_commands(args, jdk, extra_jdks):
    setvar_format = get_setvar_format(args.shell)
    shell_commands = StringIO()
    print(setvar_format % ('JAVA_HOME', jdk), file=shell_commands)
    if extra_jdks:
        print(setvar_format % ('EXTRA_JAVA_HOMES', os.pathsep.join(extra_jdks)), file=shell_commands)
    path = os.environ.get('PATH').split(os.pathsep)
    if path:
        jdk_bin = join(jdk, 'bin')
        old_java_home = os.environ.get('JAVA_HOME')
        replace = join(old_java_home, 'bin') if old_java_home else None
        if replace in path:
            path = [e if e != replace else jdk_bin for e in path]
        else:
            path = [jdk_bin] + path
        print(setvar_format % ('PATH', get_PATH_sep(args.shell).join(path)), file=shell_commands)
    return shell_commands.getvalue().strip() 
开发者ID:graalvm,项目名称:mx,代码行数:19,代码来源:select_jdk.py

示例7: test_str

# 需要导入模块: import StringIO [as 别名]
# 或者: from StringIO import StringIO [as 别名]
def test_str(self):
        """
        Test __str__ method, for full coverage and check that all modules have required attributes.
        """
        atts_list = ['PlanetPhysicalModel', 'arange', 'erange', 'Irange', 'Orange', 'wrange', 'prange',
                     'Rprange', 'Mprange', 'rrange', 'scaleOrbits', 'constrainOrbits', 'eta']
        for mod in self.allmods:
            with RedirectStreams(stdout=self.dev_null):
                obj = mod(**self.spec)
            original_stdout = sys.stdout
            sys.stdout = StringIO()
            # call __str__ method
            result = obj.__str__()
            # examine what was printed
            contents = sys.stdout.getvalue()
            self.assertEqual(type(contents), type(''))
            # attributes from ICD
            for att in atts_list:
                self.assertIn(att,contents,'{} missing for {}'.format(att,mod.__name__))
            sys.stdout.close()
            # it also returns a string, which is not necessary
            self.assertEqual(type(result), type(''))
            # put stdout back
            sys.stdout = original_stdout 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:26,代码来源:test_PlanetPopulation.py

示例8: test_str

# 需要导入模块: import StringIO [as 别名]
# 或者: from StringIO import StringIO [as 别名]
def test_str(self):
        """
        Test __str__ method, for full coverage and check that all modules have required attributes.
        """
        atts_list = ['PlanetPopulation', 'PlanetPhysicalModel', 'dMagLim', 'minComp']

        for mod in self.allmods:
            with RedirectStreams(stdout=self.dev_null):
                obj = mod(**copy.deepcopy(self.spec))
            original_stdout = sys.stdout
            sys.stdout = StringIO()
            # call __str__ method
            result = obj.__str__()
            # examine what was printed
            contents = sys.stdout.getvalue()
            self.assertEqual(type(contents), type(''))
            # attributes from ICD
            for att in atts_list:
                self.assertIn(att,contents,'{} missing for {}'.format(att,mod.__name__))
            sys.stdout.close()
            # it also returns a string, which is not necessary
            self.assertEqual(type(result), type(''))
            # put stdout back
            sys.stdout = original_stdout 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:26,代码来源:test_Completeness.py

示例9: test_str

# 需要导入模块: import StringIO [as 别名]
# 或者: from StringIO import StringIO [as 别名]
def test_str(self):
        r"""Test __str__ method, for full coverage."""
        tlist = self.fixture
        # replace stdout and keep a reference
        original_stdout = sys.stdout
        sys.stdout = StringIO()
        # call __str__ method
        result = tlist.__str__()
        # examine what was printed
        contents = sys.stdout.getvalue()
        self.assertEqual(type(contents), type(''))
        self.assertIn('PlanetPhysicalModel', contents)
        self.assertIn('PlanetPopulation', contents)
        self.assertIn('Completeness', contents)
        sys.stdout.close()
        # it also returns a string, which is not necessary
        self.assertEqual(type(result), type(''))
        # put stdout back
        sys.stdout = original_stdout

    # @unittest.skip("Skipping populate_target_list.") 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:23,代码来源:test_KnownRVPlanetsTargetList.py

示例10: test_str

# 需要导入模块: import StringIO [as 别名]
# 或者: from StringIO import StringIO [as 别名]
def test_str(self):
        """
        Test __str__ method, for full coverage and check that all modules have required attributes.
        """

        for mod in self.allmods:
            with RedirectStreams(stdout=self.dev_null):
                obj = mod()
            original_stdout = sys.stdout
            sys.stdout = StringIO()
            # call __str__ method
            result = obj.__str__()
            # examine what was printed
            contents = sys.stdout.getvalue()
            self.assertEqual(type(contents), type(''))
            # attributes from ICD
            self.assertIn('_outspec', contents,'_outspec missing for %s'%mod.__name__)
            sys.stdout.close()
            # it also returns a string, which is not necessary
            self.assertEqual(type(result), type(''))
            # put stdout back
            sys.stdout = original_stdout 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:24,代码来源:test_PlanetPhysicalModel.py

示例11: test_shouldCreateAllMigrations

# 需要导入模块: import StringIO [as 别名]
# 或者: from StringIO import StringIO [as 别名]
def test_shouldCreateAllMigrations(self):
        for f in os.listdir("river/migrations"):
            if f != "__init__.py" and f != "__pycache__" and not f.endswith(".pyc"):
                open(os.path.join("river/tests/volatile/river/", f), 'wb').write(open(os.path.join("river/migrations", f), 'rb').read())

        self.migrations_before = list(filter(lambda f: f.endswith('.py') and f != '__init__.py', os.listdir('river/tests/volatile/river/')))

        out = StringIO()
        sys.stout = out

        call_command('makemigrations', 'river', stdout=out)

        self.migrations_after = list(filter(lambda f: f.endswith('.py') and f != '__init__.py', os.listdir('river/tests/volatile/river/')))

        assert_that(out.getvalue(), equal_to("No changes detected in app 'river'\n"))
        assert_that(self.migrations_after, has_length(len(self.migrations_before))) 
开发者ID:javrasya,项目名称:django-river,代码行数:18,代码来源:test__migrations.py

示例12: dumps

# 需要导入模块: import StringIO [as 别名]
# 或者: from StringIO import StringIO [as 别名]
def dumps(obj, protocol=None):
    """Serialize obj as a string of bytes allocated in memory

    protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
    pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed
    between processes running the same Python version.

    Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
    compatibility with older versions of Python.
    """
    file = StringIO()
    try:
        cp = CloudPickler(file, protocol=protocol)
        cp.dump(obj)
        return file.getvalue()
    finally:
        file.close()


# including pickles unloading functions in this namespace 
开发者ID:pywren,项目名称:pywren-ibm-cloud,代码行数:22,代码来源:cloudpickle.py

示例13: open_local_file

# 需要导入模块: import StringIO [as 别名]
# 或者: from StringIO import StringIO [as 别名]
def open_local_file(self, req):
        host = req.get_host()
        file = req.get_selector()
        localfile = url2pathname(file)
        stats = os.stat(localfile)
        size = stats[stat.ST_SIZE]
        modified = rfc822.formatdate(stats[stat.ST_MTIME])
        mtype = mimetypes.guess_type(file)[0]
        stats = os.stat(localfile)
        headers = mimetools.Message(StringIO(
            'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
            (mtype or 'text/plain', size, modified)))
        if host:
            host, port = splitport(host)
        if not host or \
           (not port and socket.gethostbyname(host) in self.get_names()):
            return addinfourl(open(localfile, 'rb'),
                              headers, 'file:'+file)
        raise URLError('file not on local host') 
开发者ID:war-and-code,项目名称:jawfish,代码行数:21,代码来源:urllib2.py

示例14: test_same_file_as

# 需要导入模块: import StringIO [as 别名]
# 或者: from StringIO import StringIO [as 别名]
def test_same_file_as():
    fh = FileHolder('a_fname')
    assert_true(fh.same_file_as(fh))
    fh2 = FileHolder('a_test')
    assert_false(fh.same_file_as(fh2))
    sio0 = StringIO()
    fh3 = FileHolder('a_fname', sio0)
    fh4 = FileHolder('a_fname', sio0)
    assert_true(fh3.same_file_as(fh4))
    assert_false(fh3.same_file_as(fh))
    fh5 = FileHolder(fileobj=sio0)
    fh6 = FileHolder(fileobj=sio0)
    assert_true(fh5.same_file_as(fh6))
    # Not if the filename is the same
    assert_false(fh5.same_file_as(fh3))
    # pos doesn't matter
    fh4_again = FileHolder('a_fname', sio0, pos=4)
    assert_true(fh3.same_file_as(fh4_again)) 
开发者ID:ME-ICA,项目名称:me-ica,代码行数:20,代码来源:test_fileholders.py

示例15: emit

# 需要导入模块: import StringIO [as 别名]
# 或者: from StringIO import StringIO [as 别名]
def emit(events, stream=None, Dumper=Dumper,
        canonical=None, indent=None, width=None,
        allow_unicode=None, line_break=None):
    """
    Emit YAML parsing events into a stream.
    If stream is None, return the produced string instead.
    """
    getvalue = None
    if stream is None:
        from StringIO import StringIO
        stream = StringIO()
        getvalue = stream.getvalue
    dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,
            allow_unicode=allow_unicode, line_break=line_break)
    try:
        for event in events:
            dumper.emit(event)
    finally:
        dumper.dispose()
    if getvalue:
        return getvalue() 
开发者ID:remg427,项目名称:misp42splunk,代码行数:23,代码来源:__init__.py


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