本文整理汇总了Python中tempfile.TemporaryFile.close方法的典型用法代码示例。如果您正苦于以下问题:Python TemporaryFile.close方法的具体用法?Python TemporaryFile.close怎么用?Python TemporaryFile.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tempfile.TemporaryFile
的用法示例。
在下文中一共展示了TemporaryFile.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: pdf_workup
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import close [as 别名]
def pdf_workup(request, pk):
wu = get_object_or_404(models.Workup, pk=pk)
active_provider_type = get_object_or_404(ProviderType,
pk=request.session['clintype_pk'])
if active_provider_type.staff_view:
data = {'workup': wu}
template = get_template('workup/workup_body.html')
html = template.render(data)
file = TemporaryFile(mode="w+b")
pisa.CreatePDF(html.encode('utf-8'), dest=file,
encoding='utf-8')
file.seek(0)
pdf = file.read()
file.close()
initials = ''.join(name[0].upper() for name in wu.patient.name(reverse=False, middle_short=False).split())
formatdate = '.'.join([str(wu.clinic_day.clinic_date.month).zfill(2), str(wu.clinic_day.clinic_date.day).zfill(2), str(wu.clinic_day.clinic_date.year)])
filename = ''.join([initials, ' (', formatdate, ')'])
response = HttpResponse(pdf, 'application/pdf')
response["Content-Disposition"] = "attachment; filename=%s.pdf" % (filename,)
return response
else:
return HttpResponseRedirect(reverse('workup',
args=(wu.id,)))
示例2: backup
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import close [as 别名]
def backup(self):
if self.dry_run:
return
if not os.path.exists(self.config['tar']['directory']) \
or not os.path.isdir(self.config['tar']['directory']):
raise BackupError('{0} is not a directory!'.format(self.config['tar']['directory']))
out_name = "{0}.tar".format(
self.config['tar']['directory'].lstrip('/').replace('/', '_'))
outfile = os.path.join(self.target_directory, out_name)
args = ['tar', 'c', self.config['tar']['directory']]
errlog = TemporaryFile()
stream = self._open_stream(outfile, 'w')
LOG.info("Executing: %s", list2cmdline(args))
pid = Popen(
args,
stdout=stream.fileno(),
stderr=errlog.fileno(),
close_fds=True)
status = pid.wait()
try:
errlog.flush()
errlog.seek(0)
for line in errlog:
LOG.error("%s[%d]: %s", list2cmdline(args), pid.pid, line.rstrip())
finally:
errlog.close()
if status != 0:
raise BackupError('tar failed (status={0})'.format(status))
示例3: megablast_seqs
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import close [as 别名]
def megablast_seqs(seqs, params):
seq_temp = NamedTemporaryFile(bufsize=0)
seq_temp.write(LoadSeqs(data=seqs, moltype=DNA, aligned=False).toFasta())
seq_temp.flush()
out_temp = TemporaryFile()
print seq_temp.name
params['-i'] = seq_temp.name
params['-m'] = 9
print params
param_list = reduce((lambda x, y: x + y),
[[str(k), str(v)] for (k, v) in params.items()])
print param_list
proc_handle = subprocess.Popen(["megablast"] + param_list, stdout=out_temp)
proc_handle.wait()
lines = [line for line in out_temp]
print lines
blast_result = BlastResult(lines)
seq_temp.close()
out_temp.close()
return blast_result
示例4: backup
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import close [as 别名]
def backup(self, config, **flags):
# check if this is a config file
config_f = open(config, "rb")
mode = ("w:%s" % flags['compress']) if flags.get('compress') else "w"
buff = TemporaryFile()
with config_f:
cfg = ConfigParser()
cfg.readfp(config_f)
project = cfg.get("general", "project")
databases = cfg.get("general", "databases").split()
tarname = "%s.tar" % project
tar = tarfile.open(fileobj=buff, mode=mode, name=tarname)
to_close = self.__add_database_to_tar(tar, cfg, databases)
tar.close()
for f in to_close:
f.close()
buff.seek(0)
name = project + ".tar"
if flags.get('compress'):
name = project + ".t%s" % flags['compress']
if flags.get("upload"):
buff.flush()
timestamp = datetime.now().isoformat()
self.client.backup(project, name, buff, timestamp)
buff.close()
示例5: graph
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import close [as 别名]
def graph(request, type, show_name):
if not has_matplotlib:
return HttpResponse("matplotlib missing")
graph = None # TODO: get cached graph
if not graph:
graph_lock.acquire()
tmpfile = TemporaryFile()
figure = pyplot.figure(1, figsize=(4, 3))
if type == "weekday":
_weekday_graph(show_name)
elif type == "hours":
_hours_graph(show_name)
elif type == "weekday_hours":
_weekday_hours_graph(show_name)
elif type == "time_per_episode":
_time_per_episode_graph(show_name, figure)
pyplot.savefig(tmpfile, format="png")
pyplot.close(figure)
pyplot.clf()
tmpfile.seek(0)
graph = tmpfile.read()
tmpfile.close()
graph_lock.release()
return HttpResponse(graph, content_type="image/png")
示例6: SeedOutput
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import close [as 别名]
class SeedOutput(object):
def __init__(self, fd, inv, label, resp_dict):
self.__fd = fd
self.__inv = inv
self.__label = label
self.__resp_dict = resp_dict
self.__mseed_fd = TemporaryFile()
def write(self, data):
self.__mseed_fd.write(data)
def close(self):
try:
try:
seed_volume = SEEDVolume(self.__inv, ORGANIZATION, self.__label,
self.__resp_dict)
self.__mseed_fd.seek(0)
for rec in MSeedInput(self.__mseed_fd):
seed_volume.add_data(rec)
seed_volume.output(self.__fd)
except (MSeedError, SEEDError, DBError), e:
logs.error("error creating SEED volume: " + str(e))
finally:
self.__mseed_fd.close()
self.__fd.close()
示例7: CandidateUploadFile
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import close [as 别名]
class CandidateUploadFile(BaseHandler):
def initialize(self):
self.tempfile = TemporaryFile()
@tornado.web.authenticated
@granted()
@tornado.web.asynchronous
def post(self):
fp_url = self.get_argument("url")
mime_type = self.get_argument("data[type]")
size = int(self.get_argument("data[size]"))
candidate_id = self.get_argument("id")
self.candidate = self.db.query(Candidate).get(int(candidate_id))
logging.info("type: %s, size: %r", mime_type, size)
if mime_type == "image/jpeg" and size < MAX_UPLOAD_SIZE:
http_client = tornado.httpclient.AsyncHTTPClient()
request = tornado.httpclient.HTTPRequest(url=fp_url, streaming_callback=self.streaming_callback)
http_client.fetch(request, self.on_download)
else:
self.finish(dict(status=0))
def streaming_callback(self, data):
self.tempfile.write(data)
logging.info("This is the streaming_callback file tell function: %r", self.tempfile.tell())
def on_download(self, response):
img_path = os.path.join(os.path.dirname(__file__), "static/profiles/img/" + str(self.candidate.backup_id) + '.jpg')
self.tempfile.seek(0)
ptr = open(img_path, 'wb')
ptr.write(self.tempfile.read())
ptr.close()
self.tempfile.close()
self.finish(dict(src="/static/profiles/img/" + str(self.candidate.backup_id) + '.jpg', status=1))
示例8: htar
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import close [as 别名]
def htar(*args):
"""Run :command:`htar` with arguments.
Parameters
----------
args : :func:`tuple`
Arguments to be passed to :command:`htar`.
Returns
-------
:func:`tuple`
The standard output and standard error from :command:`htar`.
Raises
------
KeyError
If the :envvar:`HPSS_DIR` environment variable has not been set.
"""
outfile = TemporaryFile()
errfile = TemporaryFile()
path = get_hpss_dir()
command = [os.path.join(path, 'htar')] + list(args)
status = call(command, stdout=outfile, stderr=errfile)
outfile.seek(0)
out = outfile.read()
errfile.seek(0)
err = errfile.read()
outfile.close()
errfile.close()
return (out.decode('utf8'), err.decode('utf8'))
示例9: create_tarball
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import close [as 别名]
def create_tarball(tar_paths):
"""
Context Manger that creates the tarball of the Docker Context to use for building the image
Parameters
----------
tar_paths dict(str, str)
Key representing a full path to the file or directory and the Value representing the path within the tarball
Yields
------
The tarball file
"""
tarballfile = TemporaryFile()
with tarfile.open(fileobj=tarballfile, mode='w') as archive:
for path_on_system, path_in_tarball in tar_paths.items():
archive.add(path_on_system, arcname=path_in_tarball)
# Flush are seek to the beginning of the file
tarballfile.flush()
tarballfile.seek(0)
try:
yield tarballfile
finally:
tarballfile.close()
示例10: dataentry
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import close [as 别名]
def dataentry(self):
self.toaster.msgblockbegin("writing to temporary file")
f_tmp = TemporaryFile()
try:
total_padding = self.data.write(f_tmp)
# comparing the files will usually be different because blocks may
# have been written back in a different order, so cheaply just compare
# file sizes
self.toaster.msg("comparing file sizes")
self.stream.seek(0, 2)
f_tmp.seek(0, 2)
if self.stream.tell() != f_tmp.tell():
self.toaster.msg("original size: %i" % self.stream.tell())
self.toaster.msg("written size: %i" % f_tmp.tell())
self.toaster.msg("padding: %i" % total_padding)
if self.stream.tell() > f_tmp.tell() or self.stream.tell() + total_padding < f_tmp.tell():
f_tmp.seek(0)
f_debug = open("debug.cgf", "wb")
f_debug.write(f_tmp.read(-1))
f_debug.close()
raise Exception('write check failed: file sizes differ by more than padding')
finally:
f_tmp.close()
self.toaster.msgblockend()
# spell is finished: prevent recursing into the tree
return False
示例11: test_load_sift
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import close [as 别名]
def test_load_sift():
f = TemporaryFile()
f.write('''2 128
133.92 135.88 14.38 -2.732
3 12 23 38 10 15 78 20 39 67 42 8 12 8 39 35 118 43 17 0
0 1 12 109 9 2 6 0 0 21 46 22 14 18 51 19 5 9 41 52
65 30 3 21 55 49 26 30 118 118 25 12 8 3 2 60 53 56 72 20
7 10 16 7 88 23 13 15 12 11 11 71 45 7 4 49 82 38 38 91
118 15 2 16 33 3 5 118 98 38 6 19 36 1 0 15 64 22 1 2
6 11 18 61 31 3 0 6 15 23 118 118 13 0 0 35 38 18 40 96
24 1 0 13 17 3 24 98
132.36 99.75 11.45 -2.910
94 32 7 2 13 7 5 23 121 94 13 5 0 0 4 59 13 30 71 32
0 6 32 11 25 32 13 0 0 16 51 5 44 50 0 3 33 55 11 9
121 121 12 9 6 3 0 18 55 60 48 44 44 9 0 2 106 117 13 2
1 0 1 1 37 1 1 25 80 35 15 41 121 3 0 2 14 3 2 121
51 11 0 20 93 6 0 20 109 57 3 4 5 0 0 28 21 2 0 5
13 12 75 119 35 0 0 13 28 14 37 121 12 0 0 21 46 5 11 93
29 0 0 3 14 4 11 99''')
f.seek(0)
features = load_sift(f)
f.close()
assert_equal(len(features), 2)
assert_equal(len(features['data'][0]), 128)
assert_equal(features['row'][0], 133.92)
assert_equal(features['column'][1], 99.75)
示例12: _add_hostname_to_hosts
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import close [as 别名]
def _add_hostname_to_hosts():
"""Adds the hostname to /etc/hosts, if it is not being assigned by DNS -- required for rabbitmq
"""
hostname_file = open('/etc/hostname','r')
hostname = hostname_file.readline().rstrip()
private_ip = _get_self_private_ip()
host_found = _check_name_resolves(hostname)
if not host_found:
stdout = TemporaryFile()
stderr = TemporaryFile()
err = subprocess.call( ('/usr/bin/sudo','/usr/bin/perl', '-i.orig', '-n','-e', r"""BEGIN {($h,$ip)[email protected];
$ip='127.0.1.1' unless $ip
}
next if/\Q$h\E/;
s/^(127\.0\.0\.1\s+localhost)$/$1\n$ip $h/;
print""", hostname, private_ip, '/etc/hosts'),
stdout=stdout, stderr=stderr)
if err:
stdout.seek(0)
out='\n'.join(stdout.readlines())
stderr.seek(0)
err_text='\n'.join(stderr.readlines())
raise OSError('Error updating /etc/hosts. Result code: {0}\n{1}\n{2}'.format( err,out,err_text ))
stdout.close()
stderr.close()
示例13: _process_data_1
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import close [as 别名]
def _process_data_1(self, cr, uid, ids, data, context):
#try:
fileobj = TemporaryFile('w+')
fileobj.write(data)
fileobj.seek(0)
lines = []
for line in fileobj.readlines():
#log.info('++++++++++++++++\r\nline=%s' % line)
lines = line.split(',')
#if len(lines) == 0: break
if self._isnumeric(lines[0]) == True:
id = int(lines[0])
date_from = datetime.strptime(lines[1], '%m/%d/%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
date_to = datetime.strptime(lines[2].replace("\n",""), '%m/%d/%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
#log.info('id=%s,df=%s,dt=%s' % (id, date_from, date_to))
#check existing
day = datetime.strptime(date_from, '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d')
attds = self.pool.get('hr.attendance')
attd_ids = attds.search(cr, uid, [('employee_id','=',id),('day','=',day)], context=context)
#log.info(attd_ids)
log.info('employee_id=%d,attd_ids=%s,len=%d,day=%s' % (id,attd_ids,len(attd_ids), day))
if len(attd_ids) == 0:
attds.create(cr, uid, {'employee_id':id,'name':date_from,'action':'sign_in','source':'import'})
attds.create(cr, uid, {'employee_id':id,'name':date_to,'action':'sign_out','source':'import'})
#log.info('+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
fileobj.close()
示例14: BuildTests
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import close [as 别名]
class BuildTests(unittest.TestCase):
def setUp(self):
self.fnull = TemporaryFile()
def tearDown(self):
self._run(["./waf","distclean"])
self.fnull.close()
def _run(self, args):
sub = subprocess.Popen(args, stderr=self.fnull, stdout=self.fnull)
sub.communicate()
self.fnull.seek(0)
tail = ''.join(self.fnull.readlines()[-10:])
return sub, tail
def _configure(self, gtk, backend, delint):
arglist = ["./waf","configure","--gtk", gtk, "--backend", backend]
if delint:
arglist.append("--enable-delint")
sub, tail = self._run(arglist)
self.assertEqual(0, sub.returncode, msg=tail)
def _build(self):
sub, tail = self._run(["./waf","build"])
self.assertEqual(0, sub.returncode, msg=tail)
def _configure_and_build(self, gtk, backend, delint):
self._configure(gtk, backend, delint)
self._build()
示例15: MSeed4KOutput
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import close [as 别名]
class MSeed4KOutput(object):
def __init__(self, fd):
self.__fd = fd
self.__mseed_fd = TemporaryFile()
def write(self, data):
self.__mseed_fd.write(data)
def close(self):
try:
try:
wfd = _WaveformData()
self.__mseed_fd.seek(0)
for rec in MSeedInput(self.__mseed_fd):
wfd.add_data(rec)
wfd.output_data(self.__fd, 0)
except (MSeedError, SEEDError, DBError), e:
logs.error("error reblocking Mini-SEED data: " + str(e))
finally:
self.__mseed_fd.close()
self.__fd.close()