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