本文整理汇总了Python中tempfile.NamedTemporaryFile.writelines方法的典型用法代码示例。如果您正苦于以下问题:Python NamedTemporaryFile.writelines方法的具体用法?Python NamedTemporaryFile.writelines怎么用?Python NamedTemporaryFile.writelines使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tempfile.NamedTemporaryFile
的用法示例。
在下文中一共展示了NamedTemporaryFile.writelines方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: write_xar
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import writelines [as 别名]
def write_xar(fn, hdr, tocdata, heap, keep_old=False):
ztocdata = zlib.compress(tocdata)
digest = toc_digest(hdr, ztocdata)
newhdr = dict(hdr,
toc_length_uncompressed=len(tocdata),
toc_length_compressed=len(ztocdata))
outf = NamedTemporaryFile(prefix='.' + os.path.basename(fn),
dir=os.path.dirname(fn),
delete=False)
try:
st_mode = os.stat(fn).st_mode
if os.fstat(outf.fileno()) != st_mode:
os.fchmod(outf.fileno(), st_mode)
except OSError:
pass
try:
outf.writelines([HEADER.pack(newhdr),
ztocdata,
digest])
copyfileobj(heap, outf)
outf.close()
except:
outf.close()
os.unlink(outf.name)
raise
if keep_old:
oldfn = fn + '.old'
if os.path.exists(oldfn):
os.unlink(oldfn)
os.link(fn, oldfn)
os.rename(outf.name, fn)
示例2: setup_vcf_file
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import writelines [as 别名]
def setup_vcf_file():
"""
Print some variants to a vcf file and return the filename
"""
vcf_lines = [
'##fileformat=VCFv4.1\n',
'##INFO=<ID=MQ,Number=1,Type=Float,Description="RMS Mapping Quality">\n',
'##contig=<ID=1,length=249250621,assembly=b37>\n',
'##reference=file:///humgen/gsa-hpprojects/GATK/bundle'\
'/current/b37/human_g1k_v37.fasta\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tfather\tmother\tproband\n',
'1\t11900\t.\tA\tT\t100\tPASS\tMQ=1\tGT:GQ\t0/1:60\t0/1:60\t1/1:60\n',
'1\t879585\t.\tA\tT\t100\tPASS\tMQ=1\tGT:GQ\t0/1:60\t0/0:60\t0/1:60\n',
'1\t879586\t.\tA\tT\t100\tPASS\tMQ=1\tGT:GQ\t0/0:60\t0/1:60\t0/1:60\n',
'1\t947378\t.\tA\tT\t100\tPASS\tMQ=1\tGT:GQ\t0/0:60\t0/0:60\t0/1:60\n',
'1\t973348\t.\tG\tA\t100\tPASS\tMQ=1\tGT:GQ\t0/0:60\t0/0:60\t0/1:60\n',
'3\t879585\t.\tA\tT\t100\tPASS\tMQ=1\tGT:GQ\t0/1:60\t0/0:60\t0/1:60\n',
'3\t879586\t.\tA\tT\t100\tPASS\tMQ=1\tGT:GQ\t0/0:60\t0/1:60\t0/1:60\n',
'3\t947378\t.\tA\tT\t100\tPASS\tMQ=1\tGT:GQ\t0/0:60\t0/0:60\t0/1:60\n',
'3\t973348\t.\tG\tA\t100\tPASS\tMQ=1\tGT:GQ\t0/0:60\t0/0:60\t0/1:60\n'
]
vcf_file = NamedTemporaryFile(mode='w+t', delete=False, suffix='.vcf')
vcf_file.writelines(vcf_lines)
vcf_file.seek(0)
vcf_file.close()
return vcf_file.name
示例3: _certificate_helper
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import writelines [as 别名]
def _certificate_helper(self, private_key=None):
"""
Returns the path to a helper script which can be used in the GIT_SSH env
var to use a custom private key file.
"""
opts = {
'StrictHostKeyChecking': 'no',
'PasswordAuthentication': 'no',
'KbdInteractiveAuthentication': 'no',
'ChallengeResponseAuthentication': 'no',
}
# Create identity file
identity = NamedTemporaryFile(delete=False)
ecm.chmod(identity.name, 0600)
identity.writelines([private_key])
identity.close()
# Create helper script
helper = NamedTemporaryFile(delete=False)
helper.writelines([
'#!/bin/sh\n',
'exec ssh ' +
' '.join('-o%s=%s' % (key, value) for key, value in opts.items()) +
' -i ' + identity.name +
' $*\n'
])
helper.close()
ecm.chmod(helper.name, 0750)
return helper.name, identity.name
示例4: TestTrio
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import writelines [as 别名]
class TestTrio(object):
"""Test class for testing how the individual class behave"""
def setup_class(self):
"""Setup a standard trio."""
trio_lines = ['#Standard trio\n',
'#FamilyID\tSampleID\tFather\tMother\tSex\tPhenotype\n',
'healthyParentsAffectedSon\tproband\tfather\tmother\t1\t2\n',
'healthyParentsAffectedSon\tmother\t0\t0\t2\t1\n',
'healthyParentsAffectedSon\tfather\t0\t0\t1\t1\n'
]
self.trio_file = NamedTemporaryFile(mode='w+t', delete=False, suffix='.vcf')
self.trio_file.writelines(trio_lines)
self.trio_file.seek(0)
self.trio_file.close()
def test_standard_trio(self):
"""Test if the file is parsed in a correct way."""
family_parser = parser.FamilyParser(open(self.trio_file.name, 'r'))
assert family_parser.header == [
'family_id',
'sample_id',
'father_id',
'mother_id',
'sex',
'phenotype'
]
assert 'healthyParentsAffectedSon' in family_parser.families
assert set(['proband', 'mother', 'father']) == set(family_parser.families['healthyParentsAffectedSon'].individuals.keys())
assert set(['proband', 'mother', 'father']) == set(family_parser.families['healthyParentsAffectedSon'].trios[0])
示例5: create_template
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import writelines [as 别名]
def create_template(contents):
"""
Generate a temporary file with the specified contents as a list of strings
and yield its path as the context.
"""
template = NamedTemporaryFile(mode="w", prefix="certtool-template")
template.writelines(map(lambda l: l + "\n", contents))
template.flush()
yield template.name
template.close()
示例6: daemon
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import writelines [as 别名]
def daemon(acl, addr='localhost'):
""" Create an Rbldnsd instance with given ACL
"""
acl_zone = NamedTemporaryFile()
acl_zone.writelines("%s\n" % line for line in acl)
acl_zone.flush()
dnsd = Rbldnsd(daemon_addr=addr)
dnsd.add_dataset('acl', acl_zone)
dnsd.add_dataset('generic', ZoneFile(['test TXT "Success"']))
return dnsd
示例7: layout_graph
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import writelines [as 别名]
def layout_graph(filename):
out = NamedTemporaryFile(mode="w", delete=False)
out.writelines(_convert_dot_file(filename))
out.close() # flushes the cache
cmd = []
cmd.append("dot")
cmd.append("-Kfdp")
cmd.append("-Tpdf")
cmd.append("-Gcharset=utf-8")
cmd.append("-o{0}.pdf".format(os.path.splitext(filename)[0]))
cmd.append(out.name)
execute_command(cmd)
# Manually remove the temporary file
os.unlink(out.name)
示例8: TemporaryGenomeFile
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import writelines [as 别名]
def TemporaryGenomeFile(genome_name):
"""
returns a file-like object pointing to a temporary file containing
the chromsome names and sizes
the current file position will be 0
it will be deleted when the object is garbage collected
"""
f = NamedTemporaryFile()
genome_rows = genome(genome_name).iteritems()
f.writelines(('%s\t%d\n' for chrom, size in genome_rows))
f.flush()
f.seek(0)
return f
示例9: get_vcf_file
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import writelines [as 别名]
def get_vcf_file(vcf_lines):
"""
Take an iterator with vcf lines and prints them to a temporary file.
Arguments:
vcf_lines (iterator): An iterator with vcf lines
Returns:
filename (str): The path to the vcf file
"""
vcf_file = NamedTemporaryFile(mode='w+t', delete=False, suffix='.vcf')
vcf_file.writelines(vcf_lines)
vcf_file.seek(0)
vcf_file.close()
return vcf_file.name
示例10: get_earth_model
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import writelines [as 别名]
def get_earth_model(self, model):
"""
Check whether the specified Earth density profile has a correct
NuCraft preface. If not, create a temporary file that does.
"""
logging.debug('Trying to construct Earth model from "%s"' % model)
try:
resource_path = find_resource(model)
self.earth_model = EarthModel(resource_path)
logging.info("Loaded Earth model from %s" % model)
except SyntaxError:
# Probably the file is lacking the correct preamble
logging.info(
"Failed to construct NuCraft Earth model directly from"
" %s! Adding default preamble..." % resource_path
)
# Generate tempfile with preamble
with open(resource_path, "r") as infile:
profile_lines = infile.readlines()
preamble = [
"# nuCraft Earth model with PREM density "
"values for use as template; keep structure "
"of the first six lines unmodified!\n",
"(0.4656,0.4656,0.4957) # tuple of (relative) "
#'(0.5, 0.5, 0.5) # tuple of (relative) '
"electron numbers for mantle, outer core, " "and inner core\n",
"6371. # radius of the Earth\n",
"3480. # radius of the outer core\n",
"1121.5 # radius of the inner core\n",
"# two-columned list of radii and corresponding "
"matter density values in km and kg/dm^3; "
"add, remove or modify lines as necessary\n",
]
tfile = NamedTemporaryFile()
tfile.writelines(preamble + profile_lines)
tfile.flush()
try:
self.earth_model = EarthModel(tfile.name)
except:
logging.error("Could not construct Earth model from %s: %s" % (model, sys.exc_info()[1]))
sys.exit(1)
logging.info("Successfully constructed Earth model")
tfile.close()
except IOError:
logging.info('Using NuCraft built-in Earth model "%s"' % model)
self.earth_model = EarthModel(model)
示例11: get_ap
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import writelines [as 别名]
def get_ap(Q, data, query_name, index_names, groundtruth_dir, ranked_dir=None):
"""
Given a query, index data, and path to groundtruth data, perform the query,
and evaluate average precision for the results by calling to the compute_ap
script. Optionally save ranked results in a file.
:param ndarray Q:
query vector
:param ndarray data:
index data vectors
:param str query_name:
the name of the query
:param list index_names:
the name of index items
:param str groundtruth_dir:
directory of groundtruth files
:param str ranked_dir:
optional path to a directory to save ranked list for query
:returns float:
the average precision for this query
"""
inds, dists = get_nn(Q, data)
if ranked_dir is not None:
# Create dir for ranked results if needed
if not os.path.exists(ranked_dir):
os.makedirs(ranked_dir)
rank_file = os.path.join(ranked_dir, '%s.txt' % query_name)
f = open(rank_file, 'w')
else:
f = NamedTemporaryFile(delete=False)
rank_file = f.name
f.writelines([index_names[i] + '\n' for i in inds])
f.close()
groundtruth_prefix = os.path.join(groundtruth_dir, query_name)
cmd = './compute_ap %s %s' % (groundtruth_prefix, rank_file)
ap = os.popen(cmd).read()
# Delete temp file
if ranked_dir is None:
os.remove(rank_file)
return float(ap.strip())
示例12: __setup
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import writelines [as 别名]
def __setup(self, inputlines):
"""
Create a temporary input file and a temporary output-file.
"""
# create output file fist, so it is older
outputfile = NamedTemporaryFile("w", suffix='.json', delete=False)
outputfile.write('--- empty marker ---')
outputfile.close()
self.output_filename = outputfile.name
time.sleep(1) # ensure a time-difference between files
inputfile = NamedTemporaryFile("w", suffix='.txt', delete=False)
for line in inputlines:
inputfile.writelines((line, '\n'))
inputfile.close()
self.input_filename = inputfile.name
示例13: main
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import writelines [as 别名]
def main():
argparser = argparse.ArgumentParser(description="Call denovo variants on a VCF file containing a trio")
argparser.add_argument('--denovogear',
type=str, nargs=1,
required=True,
help='Path to the denovogear binary for example: /Users/timothyh/home/binHTS/denovogear 0.5.4/bin/denovogear'
)
argparser.add_argument('vcf_file',
type=str, nargs=1,
help='A variant file in VCF format containing the genotypes of the trio'
)
argparser.add_argument('ped_file',
type=str, nargs=1,
help='A pedigree file in .ped format containing the samples to be extracted from the VCF file'
)
print("Hello")
# Check that the PED file only contains a trio and identify sex of child as this is required for calling denovogear correctly
# Check that the VCF file contains the same samples as thePED file
# Run denovogear
#fam_id = '1'
#someFamily = family.Family(family_id = fam_id)
#print(someFamily)
trio_lines = ['#Standard trio\n',
'#FamilyID\tSampleID\tFather\tMother\tSex\tPhenotype\n',
'healthyParentsAffectedSon\tproband\tfather\tmother\t1\t2\n',
'healthyParentsAffectedSon\tmother\t0\t0\t2\t1\n',
'healthyParentsAffectedSon\tfather\t0\t0\t1\t1\n',
'healthyParentsAffectedSon\tdaughter\tfather\tmother\t2\t1\n',
]
trio_file = NamedTemporaryFile(mode='w+t', delete=False, suffix='.vcf')
trio_file.writelines(trio_lines)
trio_file.seek(0)
trio_file.close()
family_parser = parser.FamilyParser(trio_file.name)
trio_family = family_parser.families['healthyParentsAffectedSon']
print(trio_family.)
示例14: opengzip
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import writelines [as 别名]
def opengzip(fn,cb):
from tempfile import NamedTemporaryFile
from gzip import GzipFile
gzip = GzipFile(fn,'rb')
try:
tmp = NamedTemporaryFile('w+b')
try:
tmp.writelines(gzip)
tmp.flush()
cb(tmp.name)
finally:
tmp.close()
except IOError:
cb(fn)
except KeyboardInterrupt:
raise
finally:
gzip.close()
示例15: create_job
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import writelines [as 别名]
def create_job(self, commands, name=None, walltime=None, restartable=False, stagein_files=None):
if not commands: raise ValueError('SerialJobFactory.create_job: commands '
'should be a non-empty list of strings')
if not name: name = self._name
else: name = self._time_name(name)
job_file = NamedTemporaryFile(prefix=name+'-',
suffix='.job',
delete=False)
#name, stdin/stdout, nodes, etc...
job_file.writelines(['#!/bin/bash\n',
'#PBS -N %s\n' % name,
'#PBS -o %s.out\n' % name,
'#PBS -e %s.err\n' % name,
'#PBS -c enabled,shutdown,periodic\n',
'#PBS -r %s\n' %('y' if restartable else 'n'),
'#PBS -l nodes=%s\n' % self._host])
#optional
if walltime:
job_file.write('#PBS -l walltime=%s\n' % walltime)
if self._email:
job_file.write('#PBS -m abe -M %s\n' % self._email)
#stageins
if stagein_files:
stagein_files = self._prepare_stagein(stagein_files)
for f in stagein_files.values():
job_file.write('#PBS -W stagein="$TMPDIR/%(basename)[email protected]%(runner)s:%(path)s"\n'
% {'basename': f,
'runner': self._hostname,
'path': os.path.join(self._tmpdir, f)})
job_file.write('\n')
#write commands
job_file.write('cd $TMPDIR\n')
for cmd in commands:
try: cmd = cmd % stagein_files
except TypeError: pass
job_file.write(cmd+'\n')
#copy all output files back to the working directory
job_file.write(('if [[ "%(runner)s" == $(hostname) ]];\n'
'then cp -r * %(wdir)s/;\n'
'else scp -r * %(runner)s:%(wdir)s/;\n'
'fi') % {'runner': self._hostname,
'wdir': os.getcwd().replace(' ', '\ ')})
job_file.close()
return job_file.name