本文整理汇总了Python中tempfile.close函数的典型用法代码示例。如果您正苦于以下问题:Python close函数的具体用法?Python close怎么用?Python close使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了close函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: _store_output
def _store_output(self):
log.debug("Storing output ...")
tempfile = open(self._tempfile, 'r')
log.debug("Current position: " + str(self._current_position))
tempfile.seek(self._current_position)
finished = False
started = False
while self.silent and not finished:
lines = tempfile.readlines()
self._current_position = tempfile.tell()
for line in lines:
line = line.strip()
log.debug("Started: %s | Line: %s" %(str(started), line))
log.debug("Condition: " +str(line.strip().endswith(self.STARTED)))
if not started:
started = line.endswith(self.STARTED)
continue
if line.endswith(self.FINISHED):
finished = True
break
line = self._prepare_output(line)
if line:
self.output.append(line)
tempfile.close()
开发者ID:dsaran,项目名称:scripts,代码行数:30,代码来源:sqlrunner.py
示例2: Run
def Run(self, tree):
self.CreateTemporaryFiles()
tempfile = open(self.mFilenameTempInput, "w")
tempfile.write(to_string(input_tree, branchlengths=self.mBranchLengths, support=self.mSupport))
tempfile.close()
if self.mLogLevel >= 2:
os.system("cat %s" % self.mFilenameTempInput)
statement = string.join((self.mExecutable, "-v", self.mFilenameTempInput), " ")
s = subprocess.Popen(
statement,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=self.mTempDirectory,
close_fds=True,
)
(out, err) = s.communicate()
if s.returncode != 0:
raise TreeGraphError, "Error in calculating svg file\n%s" % err
d = open(self.mFilenameTempOutput).readlines()
self.DeleteTemporaryFiles()
return "".join(d)
开发者ID:CGATOxford,项目名称:Optic,代码行数:32,代码来源:tree2plot.py
示例3: tearDown
def tearDown(self):
provider_manager.unregister('fakesub = fakesubprovider:FakeSubProvider')
for patcher in self.patchers:
patcher.stop()
for tempfile in self.tempfiles:
tempfile.close()
rmtree(self.db_path)
开发者ID:NigelRook,项目名称:superliminal,代码行数:7,代码来源:test_system.py
示例4: _save_entries
def _save_entries(self):
"""
saves the file entries
"""
tempname = NamedTemporaryFile().name
# create a JSON dictionary
store_dict = {}
store_dict["max_id"] = self._max_id
entry_list = []
for entry in self._entries:
entry_dict = {}
entry_dict["filepath"] = entry.get_filepath()
entry_dict["timestamp"] = entry.get_timestamp()
entry_dict["state"] = entry.get_state()
entry_dict["entry_id"] = entry.get_entry_id()
entry_list.append(entry_dict)
store_dict["entries"] = entry_list
line = json.dumps(store_dict)
# crite JSON to temporary file
try:
tempfile = open(tempname, "w")
tempfile.write(line)
tempfile.close()
except IOError:
show_error_message("Unable to create temporary file %s." % tempname, True)
# copy encrypted temporary file to cryptstore
key = self.get_key()
fname = "cryptbox.00000001"
destpath = os.path.join(self._rootpath, fname)
encrypt_file(tempname, destpath, key)
# delete temporary file
try:
os.remove(tempname)
except OSError:
show_error_message("Unable to remove temporary file %s." % tempname)
开发者ID:joskulj,项目名称:cryptbox,代码行数:35,代码来源:cryptstore.py
示例5: kill_slaves
def kill_slaves(slave_kill_filename):
"""Kill all remote slaves which are stored in the given file.
This functions is only meant for emergency situations, when something
went wrong and the slaves have to be killed manually.
"""
tempfile = open(slave_kill_filename)
try:
for line in tempfile:
address, pid, ssh_pid = line.split(":")
pid = int(pid)
ssh_pid = int(ssh_pid)
# open ssh connection to to kill remote slave
proc = subprocess.Popen(["ssh","-T", address],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
proc.stdin.write("kill %d\n" % pid)
proc.stdin.flush()
# kill old ssh connection
try:
os.kill(ssh_pid, signal.SIGKILL)
except:
pass
# a kill might prevent the kill command transmission
# os.kill(proc.pid, signal.SIGQUIT)
print "killed slave " + address + " (pid %d)" % pid
print "all slaves killed."
finally:
tempfile.close()
开发者ID:beniamino38,项目名称:mdp-toolkit,代码行数:30,代码来源:pp_support.py
示例6: _configure_logging
def _configure_logging():
import os
import logging
log = logging.getLogger("pyoram")
formatter = logging.Formatter(
fmt=("[%(asctime)s.%(msecs)03d,"
"%(name)s,%(levelname)s] %(threadName)s %(message)s"),
datefmt="%Y-%m-%d %H:%M:%S")
level = os.environ.get("PYORAM_LOGLEVEL", "WARNING")
logfilename = os.environ.get("PYORAM_LOGFILE", None)
if len(logging.root.handlers) == 0:
# configure the logging with some sensible
# defaults.
try:
import tempfile
tempfile = tempfile.TemporaryFile(dir=".")
tempfile.close()
except OSError:
# cannot write in current directory, use the
# console logger
handler = logging.StreamHandler()
else:
if logfilename is None:
handler = logging.StreamHandler()
else:
# set up a basic logfile in current directory
handler = logging.FileHandler(logfilename)
handler.setFormatter(formatter)
handler.setLevel(level)
log.addHandler(handler)
log.setLevel(level)
log.info("PyORAM log configured using built-in "
"defaults, level=%s", level)
开发者ID:ghackebeil,项目名称:PyORAM,代码行数:35,代码来源:__init__.py
示例7: bedAnnotateDownstream
def bedAnnotateDownstream(bedFile, geneFile):
""" annotate bed features with the gene downstream of it """
tempfile = tempfile.NamedTemporaryFile()
cmd = "bedFindNeighbors %s %s --onlyDownstream > %s" % (bedFile, geneFile, tempfile.name)
util.execCmdLine(cmd)
beds = parseBedFilename(tempfile.name)
tempfile.close()
return beds
开发者ID:maximilianh,项目名称:crisporWebsite,代码行数:9,代码来源:bed.py
示例8: test_named_tempfile1
def test_named_tempfile1():
name = None
with named_tempfile() as tempfile:
name = tempfile.name
assert_true(os.path.isfile(name))
tempfile.write('hello'.encode('utf8'))
tempfile.close()
assert_true(os.path.isfile(name))
assert_false(os.path.isfile(name))
开发者ID:chebee7i,项目名称:dit,代码行数:9,代码来源:test_context.py
示例9: setUpClass
def setUpClass(cls):
# Create a predictable 296.1 MB temporary file
elements = [200, 50, 25] * 9999
cls.temp_filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data', "%s.bin" % uuid.uuid4())
tempfile = open(cls.temp_filename, 'wb')
for i in xrange(0, 9872):
tempfile.write(bytearray(elements))
tempfile.close()
开发者ID:quid,项目名称:s3concurrent,代码行数:10,代码来源:test_s3concurrent.py
示例10: browse_disptrace
def browse_disptrace(dt):
import tempfile, webbrowser, urllib, os
html = dt.render()
tempfiledes, temppath = tempfile.mkstemp(suffix='.html')
tempfile = os.fdopen(tempfiledes, "w")
tempfile.write(html)
tempfile.close()
tempurl = "file://{}".format(urllib.pathname2url(temppath))
webbrowser.get(None).open_new(tempurl)
开发者ID:atsuoishimoto,项目名称:disptrace,代码行数:10,代码来源:sample.py
示例11: test_named_tempfile2
def test_named_tempfile2():
name = None
# The specification of delete=True should be ignored.
with named_tempfile(delete=True) as tempfile:
name = tempfile.name
assert_true(os.path.isfile(name))
tempfile.write('hello'.encode('utf8'))
tempfile.close()
assert_true(os.path.isfile(name))
assert_false(os.path.isfile(name))
开发者ID:chebee7i,项目名称:dit,代码行数:10,代码来源:test_context.py
示例12: test_named_temporary_file
def test_named_temporary_file(self):
tempfile = self.client.tempfile.NamedTemporaryFile()
self.assertTrue(os.path.isfile(tempfile.name))
self.assertTrue(self.client.os.path.isfile(tempfile.name))
tempfile.close()
self.assertFalse(os.path.exists(tempfile.name))
self.assertFalse(self.client.os.path.exists(tempfile.name))
with self.client.tempfile.NamedTemporaryFile() as fh:
fh.write("hi")
fh.flush()
with open(fh.name, "rb") as local_file:
self.assertEqual(local_file.read(), "hi")
开发者ID:stestagg,项目名称:sshstdlib,代码行数:12,代码来源:sshtempfile_test.py
示例13: test_namedtemporaryfile_closes
def test_namedtemporaryfile_closes(self):
"""
The symbol django.core.files.NamedTemporaryFile is assigned as
a different class on different operating systems. In
any case, the result should minimally mock some of the API of
tempfile.NamedTemporaryFile from the Python standard library.
"""
tempfile = NamedTemporaryFile()
self.assertTrue(hasattr(tempfile, "closed"))
self.assertFalse(tempfile.closed)
tempfile.close()
self.assertTrue(tempfile.closed)
开发者ID:tsptoni,项目名称:django,代码行数:13,代码来源:tests.py
示例14: write_config
def write_config(self, config,
unlink_function=os.unlink,
temp_function=tempfile.NamedTemporaryFile):
"""Write the configuration contents to vertica.cnf file."""
LOG.debug('Defining config holder at %s.' % system.VERTICA_CONF)
tempfile = temp_function(delete=False)
try:
config.write(tempfile)
tempfile.close()
command = (("install -o root -g root -m 644 %(source)s %(target)s"
) % {'source': tempfile.name,
'target': system.VERTICA_CONF})
system.shell_execute(command)
unlink_function(tempfile.name)
except Exception:
unlink_function(tempfile.name)
raise
开发者ID:magictour,项目名称:trove,代码行数:17,代码来源:service.py
示例15: __from_wave__
def __from_wave__(cls, filename, wave_filename, compression=None):
if (str(compression) not in cls.COMPRESSION_MODES):
compression = cls.DEFAULT_COMPRESSION
#mppenc requires files to end with .mpc for some reason
if (not filename.endswith(".mpc")):
import tempfile
actual_filename = filename
tempfile = tempfile.NamedTemporaryFile(suffix=".mpc")
filename = tempfile.name
else:
actual_filename = tempfile = None
###Musepack SV7###
#sub = subprocess.Popen([BIN['mppenc'],
# "--silent",
# "--overwrite",
# "--%s" % (compression),
# wave_filename,
# filename],
# preexec_fn=ignore_sigint)
###Musepack SV8###
sub = subprocess.Popen([BIN['mpcenc'],
"--silent",
"--overwrite",
"--%s" % (compression),
wave_filename,
filename])
if (sub.wait() == 0):
if (tempfile is not None):
filename = actual_filename
f = file(filename, 'wb')
tempfile.seek(0, 0)
transfer_data(tempfile.read, f.write)
f.close()
tempfile.close()
return MusepackAudio(filename)
else:
if (tempfile is not None):
tempfile.close()
raise EncodingError(u"error encoding file with mpcenc")
开发者ID:hzlf,项目名称:python-audio-tools,代码行数:44,代码来源:__musepack__.py
示例16: _load_entries
def _load_entries(self):
"""
loads the file entries
"""
# decrypt entries file to a temporary file
key = self.get_key()
fname = "cryptbox.00000001"
srcpath = os.path.join(self._rootpath, fname)
if not os.path.isfile(srcpath):
# entry file does not exist
return
tempname = NamedTemporaryFile().name
decrypt_file(srcpath, tempname, key)
# read decrypted file
line = None
try:
tempfile = open(tempname, "r")
line = tempfile.readline()
tempfile.close()
except IOError:
show_error_message("Unable to read temporary file %s." % tempname, True)
# parse JSON content
try:
store_dict = json.loads(line)
if type(store_dict) == dict:
self._max_id = store_dict["max_id"]
entry_list = store_dict["entries"]
self._entries = []
self._entry_dict = {}
for entry_dict in entry_list:
filepath = entry_dict["filepath"]
timestamp = entry_dict["timestamp"]
state = entry_dict["state"]
entry_id = entry_dict["entry_id"]
entry = CryptStoreEntry(filepath, timestamp, state, entry_id)
self._entries.append(entry)
self._entry_dict[unicode(filepath)] = entry
except ValueError:
show_error_message("Unable to parse entry file.", False)
# delete temporary file
try:
os.remove(tempname)
except OSError:
show_error_message("Unable to remove temporary file %s." % tempname)
开发者ID:joskulj,项目名称:cryptbox,代码行数:44,代码来源:cryptstore.py
示例17: copy_to_temp
def copy_to_temp(response):
import tempfile
import shutil
(td, path) = tempfile.mkstemp()
tempfile = os.fdopen(td, "w+")
logger.debug("downloading to temporary file {0}".format(path))
try:
shutil.copyfileobj(response, tempfile)
except:
logger.debug("removing temporary file {0}".format(path))
tempfile.close()
os.remove(path)
raise
return tempfile, path
开发者ID:pestro,项目名称:pusher,代码行数:19,代码来源:http.py
示例18: _configLogging
def _configLogging():
"""Do some basic config of the logging module at package import time.
The configuring is done only if the PYRO_LOGLEVEL env var is set.
If you want to use your own logging config, make sure you do
that before any Pyro imports. Then Pyro will skip the autoconfig.
Set the env var PYRO_LOGFILE to change the name of the autoconfigured
log file (default is pyro.log in the current dir). Use '{stderr}' to
make the log go to the standard error output."""
import os
import logging
level = os.environ.get("PYRO_LOGLEVEL")
logfilename = os.environ.get("PYRO_LOGFILE", "pyro.log")
if logfilename == "{stderr}":
logfilename = None
if level is not None:
levelvalue = getattr(logging, level)
if len(logging.root.handlers) == 0:
# configure the logging with some sensible defaults.
try:
import tempfile
tempfile = tempfile.TemporaryFile(dir=".")
tempfile.close()
except OSError:
# cannot write in current directory, use the default console logger
logging.basicConfig(level=levelvalue)
else:
# set up a basic logfile in current directory
logging.basicConfig(
level=levelvalue,
filename=logfilename,
datefmt="%Y-%m-%d %H:%M:%S",
format="[%(asctime)s.%(msecs)03d,%(name)s,%(levelname)s] %(message)s"
)
log = logging.getLogger("Pyro4")
log.info("Pyro log configured using built-in defaults, level=%s", level)
else:
# PYRO_LOGLEVEL is not set, disable Pyro logging. No message is printed about this fact.
log = logging.getLogger("Pyro4")
log.setLevel(9999)
开发者ID:pmehra7,项目名称:Pyro4,代码行数:40,代码来源:__init__.py
示例19: message_open
def message_open(self, muuid, online=False):
"""Extracts the HTML Site to a Temp File and
Shows it in Webbrowser.
The Message is set read.
Temp Files are deleted in __del__ function.
"""
self.log.info('Open: %s'%muuid)
if online:
url = self.message_get_meta(muuid)['url']
webbrowser.open_new_tab(url)
else:
mime = self.message_get_meta(muuid)['mimetype']
extension = self.mimetypes.get_extension(mime)
name = str(uuid.uuid4()) + extension[0]
path = os.path.join(self.tempdir,name)
tempfile = open(path,'wb')
if extension[0] == '.html':
meta = self.message_get_meta(muuid)
data = self.message_get_data(muuid).encode(meta['encoding']).encode(meta['encoding'])
tempfile.write(data)
tempfile.close()
webbrowser.open_new_tab(path)
else:
data = self.message_get_data(muuid)
tempfile.write(data)
tempfile.close()
if sys.platform.startswith('darwin'):
subprocess.call(('open', path))
elif os.name == 'nt':
os.startfile(path)
elif os.name == 'posix':
subprocess.call(('xdg-open', path))
self.message_set_meta(muuid, 'read', True)
开发者ID:merlink01,项目名称:FeedHamster,代码行数:40,代码来源:class_feed.py
示例20: setUp
def setUp(self):
provision_device()
self.client = Client()
self.hash = hashlib.md5("DUMMYDATA".encode()).hexdigest()
self.extension = file_formats.PDF
self.filename = "{}.{}".format(self.hash, self.extension)
self.title = "[email protected]#$%^&*();'[],./?><"
self.contentnode = ContentNode(title=self.title)
self.available = True
self.preset = format_presets.DOCUMENT
self.local_file = LocalFile(id=self.hash, extension=self.extension, available=self.available)
self.file = File(local_file=self.local_file, available=self.available,
contentnode=self.contentnode, preset=self.preset)
self.path = get_content_storage_file_path(self.filename)
path_dir = os.path.dirname(self.path)
if not os.path.exists(path_dir):
os.makedirs(path_dir)
tempfile = open(self.path, "w")
tempfile.write("test")
tempfile.close()
开发者ID:indirectlylit,项目名称:kolibri,代码行数:22,代码来源:test_downloadcontent.py
注:本文中的tempfile.close函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论