本文整理汇总了Python中tempfile.NamedTemporaryFile.read方法的典型用法代码示例。如果您正苦于以下问题:Python NamedTemporaryFile.read方法的具体用法?Python NamedTemporaryFile.read怎么用?Python NamedTemporaryFile.read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tempfile.NamedTemporaryFile
的用法示例。
在下文中一共展示了NamedTemporaryFile.read方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: render
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import read [as 别名]
def render(self, media_item, width=None, height=None, options=None):
"""Generator that streams the waveform as a PNG image with a python method"""
wav_file = media_item
pngFile = NamedTemporaryFile(suffix='.png')
if not width == None:
image_width = width
else:
image_width = 1500
if not height == None:
image_height = height
else:
image_height = 200
fft_size = 2048
args = (wav_file, pngFile.name, image_width, image_height, fft_size,
self.bg_color, self.color_scheme)
create_wavform_png(*args)
buffer = pngFile.read(0xFFFF)
while buffer:
yield buffer
buffer = pngFile.read(0xFFFF)
pngFile.close()
示例2: grd_run
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import read [as 别名]
def grd_run(self, command, timeout=10):
# Create temporary files for stdout/stderr
std_out_file = NamedTemporaryFile(delete=False)
std_err_file = NamedTemporaryFile(delete=False)
# Call the command
subprocess.Popen(
args=command,
stderr=std_err_file,
stdout=std_out_file
).wait(timeout=timeout)
# Reset file pointers
std_out_file.seek(0)
std_err_file.seek(0)
# Read standard out/err
std_out = std_out_file.read().decode()
std_err = std_err_file.read().decode()
# Return results for further serialisation
return {
'stdout': std_out,
'stderr': std_err
}
示例3: ZabbixSender
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import read [as 别名]
class ZabbixSender(object):
""""""
def __init__(self,zabbix_server,zabbix_port,host,memcached_port):
self._zabbix_server = zabbix_server
self._zabbix_port = zabbix_port
self._host = host
self._memcached_port = memcached_port
self._tempfile = None
def send(self, stats):
self._write_temporary_file(stats)
self._send_data_to_zabbix()
def _write_temporary_file(self, stats):
self._tempfile = NamedTemporaryFile()
for item in stats:
self._tempfile.write(u'%s memcached_stats[%d,%s] %s\n' % (self._host,self._memcached_port,item.key,item.value))
self._tempfile.flush()
self._tempfile.seek(0)
print self._tempfile.read()
def _send_data_to_zabbix(self):
cmd = "zabbix_sender -z %s -p %d -i %s" % (self._zabbix_server,self._zabbix_port,self._tempfile.name)
#cmd = [u'zabbix_sender', u'-z',self._zabbix_server, u'-p',self._zabbix_port,u'-i', self._tempfile.name]
#call(cmd)
print cmd
os.system(cmd)
self._tempfile.close()
示例4: get_lexer
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import read [as 别名]
def get_lexer(filename):
prefix = os.path.basename(filename)[:-4]
temp = NamedTemporaryFile(prefix = prefix, suffix = "lextab.py")
lex = {}
pylly.parsespec(filename, temp.name)
exec temp.read() in lex
temp.close()
return lexer.lexer(lex['lexspec'])
示例5: TestConfiguration
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import read [as 别名]
class TestConfiguration(TestCase):
initial_data = """cluster:
name: elasticsearch-testcase
discovery:
type: ec2
http.enabled: true
node:
availability_zone: \${EC2_AZ}
instance_id: \${EC2_INSTANCE_ID}
name: test_node
data: false
master: true
path:
data: /mnt/elasticsearch/
logs: /var/log/elasticsearch
routing:
allocation:
awareness:
attributes: instance_id, availability_zone
"""
def setUp(self):
self.config_file_instance = NamedTemporaryFile()
self.config_file_instance.write(self.initial_data)
self.config_file_instance.seek(0)
def test_initial_file(self):
config = ElasticSearchConfig(Cluster("elasticsearch-testcase-master-h0slave-r01"), config_file=self.config_file_instance.name)
config.save()
# self.assertEqual(self.initial_data, self.config_file_instance.read())
self.assertDictEqual(yaml.load(self.initial_data), yaml.load(self.config_file_instance.read()))
self.config_file_instance.close()
def test_client_node(self):
self.initial_data = self.initial_data.replace("data: false", "data: false")
self.initial_data = self.initial_data.replace("master: true", "master: false")
config = ElasticSearchConfig(Cluster("elasticsearch-testcase-client-h0slave-r01"), config_file=self.config_file_instance.name)
config.save()
self.assertDictEqual(yaml.load(self.initial_data), yaml.load(self.config_file_instance.read()))
self.config_file_instance.close()
def test_master_node(self):
self.initial_data = self.initial_data.replace("data: false", "data: false")
config = ElasticSearchConfig(Cluster("elasticsearch-testcase-master-h0slave-r01"), config_file=self.config_file_instance.name)
config.save()
self.assertDictEqual(yaml.load(self.initial_data), yaml.load(self.config_file_instance.read()))
self.config_file_instance.close()
def test_data_node(self):
self.initial_data = self.initial_data.replace("master: true", "master: false")
self.initial_data = self.initial_data.replace("data: false", "data: true")
config = ElasticSearchConfig(Cluster("elasticsearch-testcase-data-h0slave-r01"), config_file=self.config_file_instance.name)
config.save()
self.assertDictEqual(yaml.load(self.initial_data), yaml.load(self.config_file_instance.read()))
self.config_file_instance.close()
示例6: get_parser
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import read [as 别名]
def get_parser(filename):
#create temporary file for the machine-generated Python stuff
prefix = os.path.basename(filename)[:-4]
temp = NamedTemporaryFile(prefix = prefix, suffix = "_gramtab.py")
pyggy.parsespec(filename, temp.name)
gram = {}
exec temp.read() in gram
g = srgram.SRGram(gram['gramspec'])
p = glr.GLR(g)
#don't need this anymore ~desu
temp.close()
return p
示例7: run_command
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import read [as 别名]
def run_command(args):
if DotNetSystem is None:
# cpython
stdout = NamedTemporaryFile()
stderr = NamedTemporaryFile()
res = subprocess.call(args, stdin=PIPE, stdout=stdout, stderr=stderr)
return stdout.read(), stderr.read(), res
else:
# IronPython
stdout = StringIO()
stderr = StringIO()
res = subprocess.call(args, stdin=PIPE, stdout=stdout, stderr=stderr)
return stdout.getvalue(), stderr.getvalue(), res
示例8: sign_csr
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import read [as 别名]
def sign_csr(self, csr, cakey, cacrt, serial_n, days, passphrase=None, ca_capable=False):
"""Sign the CSR with given CA
"""
cfg = self.__get_config_file()
logger.info( 'Signing CSR' )
if ca_capable:
extension = "v3_ca"
else:
extension = "usr_cert"
csrfile = NamedTemporaryFile()
csrfile.write(csr)
csrfile.seek(0)
cafile = NamedTemporaryFile()
cafile.write(cacrt)
cafile.seek(0)
cakeyfile = NamedTemporaryFile()
cakeyfile.write(cakey)
cakeyfile.seek(0)
certfile = NamedTemporaryFile()
command = ['x509', '-req', '-set_serial', str(serial_n),'-extfile', cfg.name , '-sha1', '-days', str(days), '-in', csrfile.name, '-CA', cafile.name, '-CAkey', cakeyfile.name, '-passin', 'stdin', '-extensions', extension, '-out', certfile.name]
self.exec_openssl(command, stdin=passphrase)
pem = certfile.read()
return pem
示例9: decrypt
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import read [as 别名]
def decrypt(self, enctext):
""" Decrypting an encrypted text by the use of a private key.
:param enctext: The encrypted text as a string
:return: The decrypted text
"""
if self.log:
self.log.info("input len: %d" % len(enctext))
_, fil = make_temp("%s" % enctext, decode=False)
ntf = NamedTemporaryFile(delete=not DEBUG)
com_list = [self.xmlsec, "--decrypt",
"--privkey-pem", self.key_file,
"--output", ntf.name,
"--id-attr:%s" % ID_ATTR, ENC_KEY_CLASS,
fil]
if self.debug:
self.log.debug("Decrypt command: %s" % " ".join(com_list))
pof = Popen(com_list, stderr=PIPE, stdout=PIPE)
p_out = pof.stdout.read()
p_err = pof.stderr.read()
if self.debug:
self.log.debug("Decrypt result (out): %s" % (p_out,))
self.log.debug("Decrypt result (err): %s" % (p_err,))
ntf.seek(0)
return ntf.read()
示例10: sign_csr
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import read [as 别名]
def sign_csr(self, csr, cakey, cacrt, serial, days, passphrase=None, ca_capable=False):
"""Sign the CSR with given CA
"""
shutil.copy(PKI_OPENSSL_CONF, self.tmpdir)
confpath = os.path.join(self.tmpdir, os.path.split(PKI_OPENSSL_CONF)[-1])
logger.info( 'Signing CSR' )
if ca_capable:
extension = "v3_ca"
else:
extension = "usr_cert"
csrfile = NamedTemporaryFile()
csrfile.write(csr)
csrfile.seek(0)
cafile = NamedTemporaryFile()
cafile.write(cacrt)
cafile.seek(0)
cakeyfile = NamedTemporaryFile()
cakeyfile.write(cakey)
cakeyfile.seek(0)
serialfile = NamedTemporaryFile()
serial = "%X" % serial
serial = serial.rjust(2,"0")
serialfile.write(serial)
serialfile.seek(0)
certfile = NamedTemporaryFile()
command = ['x509', '-req', '-CAserial', serialfile.name,'-extfile', confpath , '-sha1', '-days', str(days), '-in', csrfile.name, '-CA', cafile.name, '-CAkey', cakeyfile.name, '-passin', 'stdin', '-extensions', extension, '-out', certfile.name]
self.exec_openssl(command, stdin=passphrase)
pem = certfile.read()
return pem
示例11: _render_diffs
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import read [as 别名]
def _render_diffs(self, diffs, section_header):
"""Render diffs. Write the SECTION_HEADER iff there are actually
any diffs to render."""
w = self.output.write
section_header_printed = False
diff_temp_files = []
total_diff_size = 0
for diff in diffs:
if not diff.diff and not diff.diff_url:
continue
if not section_header_printed:
w(section_header)
section_header_printed = True
# Create a temporary file to hold this per-file diff
diff_temp_file = NamedTemporaryFile()
diff_temp_files.append(diff_temp_file)
t = diff_temp_file.write
if diff.kind == "D":
t("\nDeleted: %s\n" % diff.base_path)
elif diff.kind == "C":
t("\nCopied: %s (from r%d, %s)\n" % (diff.path, diff.base_rev, diff.base_path))
elif diff.kind == "A":
t("\nAdded: %s\n" % diff.path)
else:
# kind == 'M'
t("\nModified: %s\n" % diff.path)
if diff.diff_url:
t("URL: %s\n" % diff.diff_url)
if diff.diff:
t(SEPARATOR + "\n")
if diff.binary:
if diff.singular:
t("Binary file. No diff available.\n")
else:
t("Binary files. No diff available.\n")
else:
for line in diff.content:
t(line.raw)
diff_temp_file.flush()
temp_file_name = diff_temp_file.name
total_diff_size = total_diff_size + os.stat(temp_file_name)[stat.ST_SIZE]
if total_diff_size > MAX_DIFF_SIZE:
break
if total_diff_size > MAX_DIFF_SIZE:
w("\nNOTE: File difference information exceeds the allowed size.\n")
else:
for diff_temp_file in diff_temp_files:
diff_temp_file.seek(0)
while 1:
chunk = diff_temp_file.read(4096)
if not chunk:
break
w(chunk)
示例12: test_write_alpha_sorting
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import read [as 别名]
def test_write_alpha_sorting(self):
config_file = NamedTemporaryFile()
config_parser = VersionsConfigParser()
config_parser.add_section('Section 1')
config_parser.add_section('Section 2')
config_parser.set('Section 1', 'Option', 'Value')
config_parser.set('Section 1', 'Option-void', None)
config_parser.set('Section 1', 'Option-add+', 'Value added')
config_parser.set('Section 2', 'Option-multiline', 'Value1\nValue2')
config_parser.set('Section 2', '<', 'Value1\nValue2')
config_parser.write(config_file.name, sorting='alpha')
config_file.seek(0)
self.assertEquals(
config_file.read().decode('utf-8'),
'[Section 1]\n'
'Option = Value\n'
'Option-add += Value added\n'
'Option-void = \n'
'\n'
'[Section 2]\n'
'<= Value1\n'
' Value2\n'
'Option-multiline = Value1\n'
' Value2\n')
config_file.close()
示例13: test_seq_pipeline_parallel_run
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import read [as 别名]
def test_seq_pipeline_parallel_run(self):
'It tests that the pipeline runs ok'
pipeline = 'sanger_without_qual'
fhand_adaptors = NamedTemporaryFile()
fhand_adaptors.write(ADAPTORS)
fhand_adaptors.flush()
arabidopsis_genes = 'arabidopsis_genes+'
univec = os.path.join(TEST_DATA_DIR, 'blast', arabidopsis_genes)
configuration = {'remove_vectors': {'vectors': univec},
'remove_adaptors': {'adaptors': fhand_adaptors.name}}
in_fhands = {}
in_fhands['in_seq'] = open(os.path.join(TEST_DATA_DIR, 'seq.fasta'),
'r')
out_fhand = NamedTemporaryFile()
writer = SequenceWriter(out_fhand, file_format='fasta')
writers = {'seq': writer}
seq_pipeline_runner(pipeline, configuration, in_fhands,
processes=4, writers=writers)
out_fhand = open(out_fhand.name, 'r')
result_seq = out_fhand.read()
assert result_seq.count('>') == 6
#are we keeping the description?
assert 'mdust' in result_seq
示例14: test_merge_sam
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import read [as 别名]
def test_merge_sam():
'It merges two sams'
reference = NamedTemporaryFile(suffix='.sam')
reference.write('''>SGN-U572743
atatata
>SGN-U576692
gcgc''')
sam1 = NamedTemporaryFile(suffix='.sam')
sam1.write('''@SQ SN:SGN-U576692 LN:1714
@SQ SN:SGN-U572743 LN:833
@RG ID:g1 LB:g1 SM:g1
@RG ID:g2 LB:g2 SM:g2
SGN-E221403 0 SGN-U576692 1416 207 168M * 0 0 AGCCTGATAAAGGTCTGCCTACGTGTTTTAAGTGGAATCCGTTTCCCCATGTCCAAACCTTCTAAATAGTTTTTTGTGTTAGTTCTTGTATGCCACATACAAAAATTAACAAACTCTTTTGCCACATATGTTCCAGCACGTCAAAGCAACATGTATTTGAGCTACTTT 558<///[email protected];550300094>>FBF>>88>BBB200>@[email protected]@755225889>0..14444::[email protected]@[email protected];;84444<//,4,.,<<QFBB;::/,,,.69FBB>9:2/.409;@@>88.7,//55;[email protected],,093777777884241<:7 AS:i:160 XS:i:0 XF:i:3 XE:i:4 XN:i:0 RG:Z:g2
SGN-E221664 0 SGN-U572743 317 226 254M24S * 0 0 GGATGATCTTAGAGCTGCCATTCAAAAGATGTTAGACACTCCTGGGCCATACTTGTTGGATGTGATTGTACCTCATCAGGAGCATGTTCTACCGATGATTCCCAGTGGCGGTGCTTTCAAAAATGTGATTACGGAGGGTGATGGGAGACGTTCCTATTGACTTTGAGAAGCTACATAACTAGTTCAAGGCATTGTATTATCTAAAATAAACTTAATATTTATGTTTACTTAAAAGTTTTTCATTGTGTGAAGGAAAAAAAAAAAAAAAAAAAAAAAAA [email protected]<22-2***-,206433>:?9<,,,66:>00066=??EEAAA?B200002<<@@@=DB99777864:..0::@833099???<@488>></...<:B<<.,,[email protected]@@;;9:/9.,,,99B99233885558=?DKKKDDAA??DKBB=440/0<[email protected]@@[email protected]@@@DD:N688BBDDDBBBKKDEDDBN977?<9<111:<??==BKMPKKBB==99>QQYYYYYYYYYYYYQQ AS:i:250 XS:i:0 XF:i:0 XE:i:7 XN:i:0 RG:Z:g1
''')
sam1.flush()
sam2 = NamedTemporaryFile(suffix='.sam')
sam2.write('''@SQ SN:SGN-U576692 LN:1714
@SQ SN:SGN-U572743 LN:833
@RG ID:g1 LB:g1 SM:g1
@RG ID:g3 LB:g3 SM:g3
SGN-E200000 0 SGN-U572743 317 226 254M24S * 0 0 GGATGATCTTAGAGKTGCCATTCAAAAGATGTTAGACACTCCTGGGCCATACTTGTTGGATGTGATTGTACCTCATCAGGAGCATGTTCTACCGATGATTCCCAGTGGCGGTGCTTTCAAAAATGTGATTACGGAGGGTGATGGGAGACGTTCCTATTGACTTTGAGAAGCTACATAACTAGTTCAAGGCATTGTATTATCTAAAATAAACTTAATATTTATGTTTACTTAAAAGTTTTTCATTGTGTGAAGGAAAAAAAAAAAAAAAAAAAAAAAAA [email protected]<22-2***-,206433>:?9<,,,66:>00066=??EEAAA?B200002<<@@@=DB99777864:..0::@833099???<@488>></...<:B<<.,,[email protected]@@;;9:/9.,,,99B99233885558=?DKKKDDAA??DKBB=440/0<[email protected]@@[email protected]@@@DD:N688BBDDDBBBKKDEDDBN977?<9<111:<??==BKMPKKBB==99>QQYYYYYYYYYYYYQQ AS:i:250 XS:i:0 XF:i:0 XE:i:7 XN:i:0 RG:Z:g1
SGN-E40000 0 SGN-U576692 1416 207 168M * 0 0 AGCCTGATAAAGGTCTGCCTACGTGTTTTAAGTGGAATCCGTTTCCCCATGTCCAAACCTTCTAAATAGTTTTTTGTGTTAGTTCTTGTATGCCACATACAAAAATTAACAAACTCTTTTGCCACATATGTTCCAGCACGTCAAAGCAACATGTATTTGAGCTACTTT 558<///[email protected];550300094>>FBF>>88>BBB200>@[email protected]@755225889>0..14444::[email protected]@[email protected];;84444<//,4,.,<<QFBB;::/,,,.69FBB>9:2/.409;@@>88.7,//55;[email protected],,093777777884241<:7 AS:i:160 XS:i:0 XF:i:3 XE:i:4 XN:i:0 RG:Z:g3
''')
sam2.flush()
sam3 = NamedTemporaryFile(suffix='.sam')
merge_sam(infiles=[sam1, sam2], outfile=sam3, reference=reference)
sam3.seek(0)
sam3_content = sam3.read()
assert 'SN:SGN-U572743' in sam3_content
assert 'SGN-E200000' in sam3_content
assert 'SGN-E221664' in sam3_content
示例15: xls_export
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import read [as 别名]
def xls_export(request, username, id_string):
owner = get_object_or_404(User, username=username)
xform = get_object_or_404(XForm, id_string=id_string, user=owner)
if not has_permission(xform, owner, request):
return HttpResponseForbidden(_(u"Not shared."))
query = request.GET.get("query")
force_xlsx = request.GET.get("xlsx") == "true"
xls_df_builder = XLSDataFrameBuilder(username, id_string, query)
excel_defs = {
"xls": {"suffix": ".xls", "mime_type": "vnd.ms-excel"},
"xlsx": {"suffix": ".xlsx", "mime_type": "vnd.openxmlformats"}, # TODO: check xlsx mime type
}
ext = "xls" if not force_xlsx else "xlsx"
if xls_df_builder.exceeds_xls_limits:
ext = "xlsx"
try:
temp_file = NamedTemporaryFile(suffix=excel_defs[ext]["suffix"])
xls_df_builder.export_to(temp_file.name)
if request.GET.get("raw"):
id_string = None
response = response_with_mimetype_and_name(excel_defs[ext]["mime_type"], id_string, extension=ext)
response.write(temp_file.read())
temp_file.seek(0, os.SEEK_END)
response["Content-Length"] = temp_file.tell()
temp_file.close()
return response
except NoRecordsFoundError:
return HttpResponse(_("No records found to export"))