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


Python six.StringIO方法代码示例

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


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

示例1: import_schema_from_astore_output

# 需要导入模块: import six [as 别名]
# 或者: from six import StringIO [as 别名]
def import_schema_from_astore_output(self, output_variables_input):
        '''
        Import a schema from the astore CAS action output format

        Parameters
        ----------
        output_variables_input : DataFrame or list or string
            The schema definition

        '''
        if isinstance(output_variables_input, six.string_types):
            if os.path.isfile(output_variables_input):
                output_variables_input = pd.read_csv(output_variables_input)
            else:
                output_variables_input = pd.read_csv(six.StringIO(output_variables_input))
        if isinstance(output_variables_input, pd.DataFrame):
            self.schema = self._create_schema_list(output_variables_input)
        elif isinstance(output_variables_input, (tuple, list)):
            self.schema = list(output_variables_input) 
开发者ID:sassoftware,项目名称:python-esppy,代码行数:21,代码来源:score.py

示例2: preProcessCSS

# 需要导入模块: import six [as 别名]
# 或者: from six import StringIO [as 别名]
def preProcessCSS(cnt, partial=""):
    """ Apply css-preprocessing on css rules (according css.type) using a partial or not
        return the css pre-processed
    """
    if cnt.type in ["scss", "sass"]:
        if hasSass:
            from scss.compiler import compile_string  # lang="scss"

            return compile_string(partial + "\n" + cnt.value)
        else:
            print("***WARNING*** : miss 'sass' preprocessor : sudo pip install pyscss")
            return cnt.value
    elif cnt.type in ["less"]:
        if hasLess:
            import lesscpy, six

            return lesscpy.compile(
                six.StringIO(partial + "\n" + cnt.value), minify=True
            )
        else:
            print("***WARNING*** : miss 'less' preprocessor : sudo pip install lesscpy")
            return cnt.value
    else:
        return cnt.value 
开发者ID:manatlan,项目名称:vbuild,代码行数:26,代码来源:__init__.py

示例3: get

# 需要导入模块: import six [as 别名]
# 或者: from six import StringIO [as 别名]
def get(self, handler, *args, **kwargs):
        f = StringIO()
        for timestamp, predictions in handler.server.server.events_queue:
            data = {
                'timestamp': '{:%Y-%m-%d %H:%M:%S}'.format(timestamp),
                'predictions': predictions
            }
            f.writelines(self.render_template('event.html', **data))

        response = f.getvalue()
        f.close()

        handler.send_response(http_client.OK)
        handler.send_header('Content-type', 'text/html')
        handler.end_headers()
        handler.wfile.write(response.encode()) 
开发者ID:devicehive,项目名称:devicehive-audio-analysis,代码行数:18,代码来源:controllers.py

示例4: compute_content

# 需要导入模块: import six [as 别名]
# 或者: from six import StringIO [as 别名]
def compute_content(self, layout):
        """trick to compute the formatting of children layout before actually
        writing it

        return an iterator on strings (one for each child element)
        """
        # Patch the underlying output stream with a fresh-generated stream,
        # which is used to store a temporary representation of a child
        # node.
        out = self.out
        try:
            for child in layout.children:
                stream = six.StringIO()
                self.out = stream
                child.accept(self)
                yield stream.getvalue()
        finally:
            self.out = out 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:20,代码来源:__init__.py

示例5: test_values_from_configuration_file

# 需要导入模块: import six [as 别名]
# 或者: from six import StringIO [as 别名]
def test_values_from_configuration_file(self, os, open):
        """Values retrieved from configuration file."""
        expected = {
            "api_key": "<api_key>",
            "api_server": "<api_server",
            "timeout": 123456,
        }

        os.environ = {}
        os.path.isfile.return_value = True
        file_content = textwrap.dedent(
            """\
            [greynoise]
            api_key = {}
            api_server = {}
            timeout = {}
            """.format(
                expected["api_key"], expected["api_server"], expected["timeout"],
            )
        )
        open().__enter__.return_value = StringIO(file_content)

        config = load_config()
        assert config == expected
        open().__enter__.assert_called() 
开发者ID:GreyNoise-Intelligence,项目名称:pygreynoise,代码行数:27,代码来源:test_util.py

示例6: test_api_key_from_environment_variable

# 需要导入模块: import six [as 别名]
# 或者: from six import StringIO [as 别名]
def test_api_key_from_environment_variable(self, os, open):
        """API key value retrieved from environment variable."""
        expected = {
            "api_key": "<api_key>",
            "api_server": "<api_server>",
            "timeout": 123456,
        }

        os.environ = {"GREYNOISE_API_KEY": expected["api_key"]}
        os.path.isfile.return_value = True
        file_content = textwrap.dedent(
            """\
            [greynoise]
            api_key = unexpected
            api_server = {}
            timeout = {}
            """.format(
                expected["api_server"], expected["timeout"],
            )
        )
        open().__enter__.return_value = StringIO(file_content)

        config = load_config()
        assert config == expected
        open().__enter__.assert_called() 
开发者ID:GreyNoise-Intelligence,项目名称:pygreynoise,代码行数:27,代码来源:test_util.py

示例7: test_api_server_from_environment_variable

# 需要导入模块: import six [as 别名]
# 或者: from six import StringIO [as 别名]
def test_api_server_from_environment_variable(self, os, open):
        """API server value retrieved from environment variable."""
        expected = {
            "api_key": "<api_key>",
            "api_server": "<api_server>",
            "timeout": 123456,
        }

        os.environ = {"GREYNOISE_API_SERVER": expected["api_server"]}
        os.path.isfile.return_value = True
        file_content = textwrap.dedent(
            """\
            [greynoise]
            api_key = {}
            api_server = unexpected
            timeout = {}
            """.format(
                expected["api_key"], expected["timeout"],
            )
        )
        open().__enter__.return_value = StringIO(file_content)

        config = load_config()
        assert config == expected
        open().__enter__.assert_called() 
开发者ID:GreyNoise-Intelligence,项目名称:pygreynoise,代码行数:27,代码来源:test_util.py

示例8: test_timeout_from_environment_variable

# 需要导入模块: import six [as 别名]
# 或者: from six import StringIO [as 别名]
def test_timeout_from_environment_variable(self, os, open):
        """Timeout value retrieved from environment variable."""
        expected = {
            "api_key": "<api_key>",
            "api_server": "<api_server>",
            "timeout": 123456,
        }

        os.environ = {"GREYNOISE_TIMEOUT": str(expected["timeout"])}
        os.path.isfile.return_value = True
        file_content = textwrap.dedent(
            """\
            [greynoise]
            api_key = {}
            api_server = {}
            timeout = unexpected
            """.format(
                expected["api_key"], expected["api_server"],
            )
        )
        open().__enter__.return_value = StringIO(file_content)

        config = load_config()
        assert config == expected
        open().__enter__.assert_called() 
开发者ID:GreyNoise-Intelligence,项目名称:pygreynoise,代码行数:27,代码来源:test_util.py

示例9: test_timeout_from_environment_variable_with_invalid_value

# 需要导入模块: import six [as 别名]
# 或者: from six import StringIO [as 别名]
def test_timeout_from_environment_variable_with_invalid_value(self, os, open):
        """Invalid timeout value in environment variable is ignored."""
        expected = {
            "api_key": "<api_key>",
            "api_server": "<api_server>",
            "timeout": 123456,
        }

        os.environ = {"GREYNOISE_TIMEOUT": "invalid"}
        os.path.isfile.return_value = True
        file_content = textwrap.dedent(
            """\
            [greynoise]
            api_key = {}
            api_server = {}
            timeout = {}
            """.format(
                expected["api_key"], expected["api_server"], expected["timeout"],
            )
        )
        open().__enter__.return_value = StringIO(file_content)

        config = load_config()
        assert config == expected
        open().__enter__.assert_called() 
开发者ID:GreyNoise-Intelligence,项目名称:pygreynoise,代码行数:27,代码来源:test_util.py

示例10: test_input_file_invalid_ip_addresses_passsed

# 需要导入模块: import six [as 别名]
# 或者: from six import StringIO [as 别名]
def test_input_file_invalid_ip_addresses_passsed(self, api_client):
        """Error returned if only invalid IP addresses are passed in input file."""
        runner = CliRunner()

        expected = (
            "Error: at least one valid IP address must be passed either as an "
            "argument (IP_ADDRESS) or through the -i/--input_file option."
        )

        result = runner.invoke(
            subcommand.interesting,
            ["-i", StringIO("not-an-ip")],
            parent=Context(main, info_name="greynoise"),
        )
        assert result.exit_code == -1
        assert "Usage: greynoise interesting" in result.output
        assert expected in result.output
        api_client.interesting.assert_not_called() 
开发者ID:GreyNoise-Intelligence,项目名称:pygreynoise,代码行数:20,代码来源:test_subcommand.py

示例11: test_empty_input_file

# 需要导入模块: import six [as 别名]
# 或者: from six import StringIO [as 别名]
def test_empty_input_file(self, api_client):
        """Error is returned if empty input fle is passed."""
        runner = CliRunner()

        expected = (
            "Error: at least one query must be passed either as an argument "
            "(QUERY) or through the -i/--input_file option."
        )

        result = runner.invoke(
            subcommand.query,
            ["-i", StringIO()],
            parent=Context(main, info_name="greynoise"),
        )
        assert result.exit_code == -1
        assert "Usage: greynoise query" in result.output
        assert expected in result.output
        api_client.query.assert_not_called() 
开发者ID:GreyNoise-Intelligence,项目名称:pygreynoise,代码行数:20,代码来源:test_subcommand.py

示例12: _in_process_execute

# 需要导入模块: import six [as 别名]
# 或者: from six import StringIO [as 别名]
def _in_process_execute(self, command):
        cli_name_prefixed = '{} '.format(self.cli.name)
        if command.startswith(cli_name_prefixed):
            command = command[len(cli_name_prefixed):]

        out_buffer = six.StringIO()
        try:
            # issue: stderr cannot be redirect in this form, as a result some failure information
            # is lost when command fails.
            self.exit_code = self.cli.invoke(shlex.split(command), out_file=out_buffer) or 0
            self.output = out_buffer.getvalue()
        except vcr.errors.CannotOverwriteExistingCassetteException as ex:
            raise AssertionError(ex)
        except CliExecutionError as ex:
            if ex.exception:
                raise ex.exception
            raise ex
        except Exception as ex:  # pylint: disable=broad-except
            self.exit_code = 1
            self.output = out_buffer.getvalue()
            self.process_error = ex
        finally:
            out_buffer.close() 
开发者ID:microsoft,项目名称:knack,代码行数:25,代码来源:base.py

示例13: redirect_io

# 需要导入模块: import six [as 别名]
# 或者: from six import StringIO [as 别名]
def redirect_io(func):

    original_stderr = sys.stderr
    original_stdout = sys.stdout

    def wrapper(self):
        sys.stdout = sys.stderr = self.io = StringIO()
        func(self)
        self.io.close()
        sys.stdout = original_stderr
        sys.stderr = original_stderr

        # Remove the handlers added by CLI, so that the next invoke call init them again with the new stderr
        # Otherwise, the handlers will write to a closed StringIO from a preview test
        root_logger = logging.getLogger()
        cli_logger = logging.getLogger(CLI_LOGGER_NAME)
        root_logger.handlers = root_logger.handlers[:-1]
        cli_logger.handlers = cli_logger.handlers[:-1]
    return wrapper 
开发者ID:microsoft,项目名称:knack,代码行数:21,代码来源:util.py

示例14: exception_traceback

# 需要导入模块: import six [as 别名]
# 或者: from six import StringIO [as 别名]
def exception_traceback(exc_info=None):
    """
    Return a string containing a traceback message for the given
    exc_info tuple (as returned by sys.exc_info()).

    from setuptools.tests.doctest
    """

    if not exc_info:
        exc_info = sys.exc_info()

    # Get a traceback message.
    excout = StringIO()
    exc_type, exc_val, exc_tb = exc_info
    traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
    return excout.getvalue() 
开发者ID:jpmens,项目名称:mqttwarn,代码行数:18,代码来源:util.py

示例15: _load_file_from_gcs

# 需要导入模块: import six [as 别名]
# 或者: from six import StringIO [as 别名]
def _load_file_from_gcs(gcs_file_path, credentials=None):
  """Load context from a text file in gcs.

  Args:
    gcs_file_path: The target file path; should have the 'gs://' prefix.
    credentials: Optional credential to be used to load the file from gcs.

  Returns:
    The content of the text file as a string.
  """
  gcs_service = _get_storage_service(credentials)

  bucket_name, object_name = gcs_file_path[len('gs://'):].split('/', 1)
  request = gcs_service.objects().get_media(
      bucket=bucket_name, object=object_name)

  file_handle = io.BytesIO()
  downloader = MediaIoBaseDownload(file_handle, request, chunksize=1024 * 1024)
  done = False
  while not done:
    _, done = _downloader_next_chunk(downloader)
  filevalue = file_handle.getvalue()
  if not isinstance(filevalue, six.string_types):
    filevalue = filevalue.decode()
  return six.StringIO(filevalue) 
开发者ID:DataBiosphere,项目名称:dsub,代码行数:27,代码来源:dsub_util.py


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