本文整理汇总了Python中six.StringIO.seek方法的典型用法代码示例。如果您正苦于以下问题:Python StringIO.seek方法的具体用法?Python StringIO.seek怎么用?Python StringIO.seek使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.StringIO
的用法示例。
在下文中一共展示了StringIO.seek方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_api_key_should_be_revoked
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import seek [as 别名]
def test_api_key_should_be_revoked(self):
user = user_factory(id=67890)
# The test csv contains an entry with this user and the "right" secret.
right_secret = (
'ab2228544a061cb2af21af97f637cc58e1f8340196f1ddc3de329b5974694b26')
apikey = APIKey.objects.create(
key='user:{}:{}'.format(user.pk, '333'), secret=right_secret,
user=user, is_active=True)
stdout = StringIO()
call_command('revoke_api_keys', self.csv_path, stdout=stdout)
stdout.seek(0)
output = stdout.readlines()
assert output[0] == (
'Ignoring APIKey user:12345:666, it does not exist.\n')
assert output[1] == (
'Revoked APIKey user:67890:333.\n')
assert output[2] == (
'Ignoring APIKey garbage, it does not exist.\n')
assert output[3] == (
'Done. Revoked 1 keys out of 3 entries.\n')
# API key is now inactive, secret hasn't changed, the other user api
# key is still there, there are no additional APIKeys.
apikey.reload()
assert apikey.secret == right_secret
assert apikey.is_active is None
assert APIKey.objects.filter(user=user).count() == 2
assert APIKey.objects.filter(user=user, is_active=True).count() == 1
示例2: runquery_csv
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import seek [as 别名]
def runquery_csv():
global out
q = frappe.form_dict.get('query')
rep_name = frappe.form_dict.get('report_name')
if not frappe.form_dict.get('simple_query'):
# Report Name
if not rep_name:
rep_name = get_sql_tables(q)[0]
if not rep_name: rep_name = 'DataExport'
rows = [[rep_name], out['colnames']] + out['values']
from six import StringIO
import csv
f = StringIO()
writer = csv.writer(f)
for r in rows:
# encode only unicode type strings and not int, floats etc.
writer.writerow(map(lambda v: isinstance(v, text_type) and v.encode('utf-8') or v, r))
f.seek(0)
out['result'] = text_type(f.read(), 'utf-8')
out['type'] = 'csv'
out['doctype'] = rep_name
示例3: load_dataset
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import seek [as 别名]
def load_dataset(infile, selection, verbose=1, **kwargs):
"""
Loads selected distribution from selected infile.
Arguments:
infile (str): Path to text input file
selection (str): Start of lines containing desired dataset
verbose (int): Level of verbose output
Returns:
dataset (DataFrame): Selected dataset
"""
from six import StringIO
import pandas
if verbose >= 1:
print("loading '{0}' from '{1}'".format(selection, infile))
s = StringIO()
with open(infile) as open_infile:
for line in open_infile:
if line.startswith(selection):
s.write(line)
s.seek(0)
dataset = pandas.read_csv(s, delim_whitespace=True, header=None,
usecols=[3,4,5,6], names=["phi", "psi", "probability",
"free energy"])
return dataset
示例4: test_dump_and_load
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import seek [as 别名]
def test_dump_and_load(self):
in_resource = Book(
title='Consider Phlebas',
isbn='0-333-45430-8',
num_pages=471,
rrp=19.50,
fiction=True,
genre="sci-fi",
authors=[Author(name="Iain M. Banks")],
publisher=Publisher(name="Macmillan"),
published=[datetime.datetime(1987, 1, 1)]
)
fp = StringIO()
yaml_codec.dump(in_resource, fp)
fp.seek(0)
out_resource = yaml_codec.load(fp)
self.assertEqual(out_resource.title, in_resource.title)
self.assertEqual(out_resource.isbn, in_resource.isbn)
self.assertEqual(out_resource.num_pages, in_resource.num_pages)
self.assertEqual(out_resource.rrp, in_resource.rrp)
self.assertEqual(out_resource.fiction, in_resource.fiction)
self.assertEqual(out_resource.genre, in_resource.genre)
self.assertEqual(out_resource.authors[0].name, in_resource.authors[0].name)
self.assertEqual(out_resource.publisher.name, in_resource.publisher.name)
self.assertEqual(out_resource.published[0], in_resource.published[0])
示例5: test_discover
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import seek [as 别名]
def test_discover(self):
org = 'quay.io/cogniteev'
truncated_config = StringIO()
config = load_config(self.CONFIG_FILE)
config['organizations'][org]['repositories'] = None
save_config(config, truncated_config)
truncated_config.seek(0, 0)
discover_command(['cogniteev'], truncated_config, interactive=False)
config = load_config(self.CONFIG_FILE)
tags = config.get('organizations', {})\
.get('quay.io/cogniteev', {})\
.get('repositories', {})\
.get('docido-contrib-crawlers', {})\
.get('on_build', {})\
.get('tags', {})
self.assertEqual(len(tags), 1)
latest_trigger = tags.get('latest')
self.assertEqual(len(latest_trigger), 1)
github_repo = 'quay.io/cogniteev/docido-pull-crawler-github'
assertCountEqual(
self,
latest_trigger.get(github_repo),
[
dict(trigger_uuid="dcb1e958-9fdb-4e9b-9856-4d52771b3df9",
ref="refs/heads/develop"),
dict(trigger_uuid="567da7a3-0373-4cf2-8480-58a18b8dbe47",
ref="refs/tags/v1.1"),
]
)
示例6: test_roundtrip_biological_sequences
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import seek [as 别名]
def test_roundtrip_biological_sequences(self):
fps = list(map(lambda e: list(map(get_data_path, e)),
[('fasta_multi_seq_roundtrip',
'qual_multi_seq_roundtrip'),
('fasta_sequence_collection_different_type',
'qual_sequence_collection_different_type')]))
for reader, writer in ((_fasta_to_biological_sequence,
_biological_sequence_to_fasta),
(partial(_fasta_to_dna_sequence,
validate=False),
_dna_sequence_to_fasta),
(partial(_fasta_to_rna_sequence,
validate=False),
_rna_sequence_to_fasta),
(partial(_fasta_to_protein_sequence,
validate=False),
_protein_sequence_to_fasta)):
for fasta_fp, qual_fp in fps:
# read
obj1 = reader(fasta_fp, qual=qual_fp)
# write
fasta_fh = StringIO()
qual_fh = StringIO()
writer(obj1, fasta_fh, qual=qual_fh)
fasta_fh.seek(0)
qual_fh.seek(0)
# read
obj2 = reader(fasta_fh, qual=qual_fh)
fasta_fh.close()
qual_fh.close()
self.assertEqual(obj1, obj2)
示例7: do_POST
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import seek [as 别名]
def do_POST(self):
"""Serve a POST request."""
r, info = self.deal_post_data()
print(r, info, "by: ", self.client_address)
f = StringIO()
f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
f.write("<html>\n<title>Upload Result Page</title>\n")
f.write("<body>\n<h2>Upload Result Page</h2>\n")
f.write("<hr>\n")
if r:
f.write("<strong>Success:</strong>")
else:
f.write("<strong>Failed:</strong>")
f.write(info)
f.write("<br><a href=\"%s\">back</a>" % self.headers['referer'])
f.write("<hr><small>Powerd By: bones7456, check new version at ")
f.write("<a href=\"http://li2z.cn/?s=SimpleHTTPServerWithUpload\">")
f.write("here</a>.</small></body>\n</html>\n")
length = f.tell()
f.seek(0)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Content-Length", str(length))
self.end_headers()
if f:
self.copyfile(f, self.wfile)
f.close()
示例8: __init__
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import seek [as 别名]
def __init__(self, settings=None, setup=True, check=False):
if isinstance(settings, six.string_types):
settingsfile = StringIO()
settings = re.sub(r" *\\\n *", " ", settings)
settingsfile.write(settings)
settingsfile.seek(0)
self.settings = configobj.ConfigObj(
settingsfile,
configspec=os.path.join(config.CONFIG_DIR, "settings.spec"))
tools.cobj_check(self.settings, exception=PyfigError)
elif check:
self.settings = configobj.ConfigObj(
settings,
configspec=os.path.join(config.CONFIG_DIR, "settings.spec"))
tools.cobj_check(self.settings, exception=PyfigError)
else:
self.settings = settings
self.rows = []
self.cols = []
self.title = None
self.repo = self._get_repo()
self.plotlines = collections.defaultdict(list)
self.labels = collections.defaultdict(list)
self.style = collections.defaultdict(
lambda: collections.defaultdict(dict))
if setup:
matplotlib.figure.Figure.__init__(
self, figsize=self.settings["figsize"])
self.setup()
示例9: test_write_csv_to_stream
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import seek [as 别名]
def test_write_csv_to_stream():
observation = OrderedDict([
('datetime', datetime.datetime(2015, 1, 24, 18, tzinfo=pytz.UTC)),
('wind_direction', 'W'),
('wind_direction_degrees', 270.0),
('pressure_tendency', 'R'),
('screen_relative_humidity', 82.5),
('pressure', 1029.0),
('wind_speed', 16.0),
('temperature', 6.1),
('weather_type', 'Overcast'),
('visibility', 9000.0),
('dew_point', 3.4),
])
stream = StringIO()
write_csv_to_stream(stream, [observation])
stream.seek(0)
lines = stream.read().split('\r\n')
expected_header = (
'datetime,wind_direction,wind_direction_degrees,pressure_tendency,'
'screen_relative_humidity,pressure,wind_speed,wind_gust,temperature,'
'weather_type,visibility,dew_point')
expected_line_1 = ','.join([
'2015-01-24T18:00:00Z', 'W', '270.0', 'R', '82.5', '1029.0', '16.0',
'', '6.1', 'Overcast', '9000.0', '3.4'])
yield assert_equal, expected_header, lines[0]
yield assert_equal, expected_line_1, lines[1]
示例10: test_deprecated_io
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import seek [as 别名]
def test_deprecated_io(self):
fh = StringIO()
npt.assert_warns(DeprecationWarning, self.ordination_results.to_file, fh)
fh.seek(0)
deserialized = npt.assert_warns(DeprecationWarning, OrdinationResults.from_file, fh)
assert_ordination_results_equal(deserialized, self.ordination_results)
self.assertTrue(type(deserialized) == OrdinationResults)
示例11: basic_config
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import seek [as 别名]
def basic_config(config_file):
from six import StringIO
import yaml
buff = StringIO()
buff.write(config_file)
buff.seek(0)
return Config.from_dict(yaml.load(buff))
示例12: _parse_config
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import seek [as 别名]
def _parse_config():
"""Parse the config file, set up defaults.
"""
defaults = {'apikey': apikey,
'server': server,
'verbosity': 0,
'cachedir': os.path.expanduser('~/.openml/cache'),
'avoid_duplicate_runs': 'True'}
config_file = os.path.expanduser('~/.openml/config')
config = configparser.RawConfigParser(defaults=defaults)
if not os.path.exists(config_file):
# Create an empty config file if there was none so far
fh = open(config_file, "w")
fh.close()
logger.info("Could not find a configuration file at %s. Going to "
"create an empty file there." % config_file)
try:
# Cheat the ConfigParser module by adding a fake section header
config_file_ = StringIO()
config_file_.write("[FAKE_SECTION]\n")
with open(config_file) as fh:
for line in fh:
config_file_.write(line)
config_file_.seek(0)
config.readfp(config_file_)
except OSError as e:
logging.info("Error opening file %s: %s" %
config_file, e.message)
return config
示例13: test_start_subshell
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import seek [as 别名]
def test_start_subshell(self, call_mock, tempfile_mock):
memfile = StringIO()
memfile.name = 'FILENAME'
tempfile_mock.return_value = memfile
credentials = {'AWS_VALID_SECONDS': 600}
start_subshell(credentials, 'ACCOUNT', 'ROLE')
call_mock.assert_called_once_with(
["bash", "--rcfile", 'FILENAME'],
stdout=sys.stdout, stderr=sys.stderr, stdin=sys.stdin)
expected = dedent("""
# Pretend to be an interactive, non-login shell
for file in /etc/bash.bashrc ~/.bashrc; do
[ -f "$file" ] && . "$file"
done
function afp_minutes_left {
if ((SECONDS >= 600)) ; then
echo EXPIRED
else
echo $(((600-SECONDS)/60)) Min
fi
}
PS1="(AWS ACCOUNT/ROLE \$(afp_minutes_left)) $PS1"
export AWS_VALID_SECONDS='600'""")
memfile.seek(0)
received = memfile.read()
self.assertEqual(received, expected)
示例14: test_export_csv_with_dialect
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import seek [as 别名]
def test_export_csv_with_dialect(self):
output_file = StringIO()
self.t.to_csv(output_file=output_file, dialect="excel")
output_file.seek(0)
reader = csv.DictReader(output_file, dialect="excel")
row = next(reader)
self.assertEqual(row, {"A":"1", "B":"0.0", "C":"x"})
示例15: test_fetch
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import seek [as 别名]
def test_fetch(self, mocked_urlopen):
mresponse = StringIO()
mresponse.write('structureId,chainId,structureTitle,compound,ecNo,uniprotAcc,uniprotRecommendedName\n')
mresponse.write('"104L","B","HOW AMINO-ACID INSERTIONS ARE ALLOWED IN AN ALPHA-HELIX OF T4 LYSOZYME","T4 LYSOZYME","3.2.1.17","P00720","Endolysin"\n')
mresponse.write('"12E8","H","2E8 FAB FRAGMENT","IGG1-KAPPA 2E8 FAB (HEAVY CHAIN)","","",""\n')
mresponse.seek(0)
mocked_urlopen.return_value = mresponse
pdb_report = PdbReport(['104L', '12E8'])
pdbs = list(pdb_report.fetch())
expected = [{
'chainId': 'B',
'structureId': '104L',
'structureTitle': 'HOW AMINO-ACID INSERTIONS ARE ALLOWED IN AN ALPHA-HELIX OF T4 LYSOZYME',
'ecNo': '3.2.1.17',
'uniprotAcc': 'P00720',
'compound': 'T4 LYSOZYME',
'uniprotRecommendedName': 'Endolysin'
}, {
'chainId': 'H',
'structureId': '12E8',
'structureTitle': '2E8 FAB FRAGMENT',
'ecNo': None,
'uniprotAcc': None,
'compound': 'IGG1-KAPPA 2E8 FAB (HEAVY CHAIN)',
'uniprotRecommendedName': None
}]
eq_(pdbs, expected)