本文整理匯總了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)
示例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
示例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())
示例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
示例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()
示例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()
示例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()
示例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()
示例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()
示例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()
示例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()
示例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()
示例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
示例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()
示例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)