本文整理匯總了Python中tempfile.mkstemp方法的典型用法代碼示例。如果您正苦於以下問題:Python tempfile.mkstemp方法的具體用法?Python tempfile.mkstemp怎麽用?Python tempfile.mkstemp使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類tempfile
的用法示例。
在下文中一共展示了tempfile.mkstemp方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_num_triggering_samples
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import mkstemp [as 別名]
def get_num_triggering_samples(signature, samples):
"""
Get number of samples triggering ClamAV signature _signature_.
:param signature: A dictionary with keys 'type' for the signature type
and 'signature' for the signature string.
:param samples: A list of sample paths to scan.
:returns: The number of samples triggering this signature.
"""
handle, temp_sig = tempfile.mkstemp(suffix = "." + signature["type"])
try:
with os.fdopen(handle, "w") as f:
f.write(signature["signature"])
proc_clamscan = subprocess.Popen(["clamscan",
"-d", temp_sig,
"--no-summary", "--infected"] + samples,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE)
stdout, stderr = proc_clamscan.communicate()
if not stdout:
return 0
else:
return len(stdout.strip().split("\n"))
finally:
os.unlink(temp_sig)
示例2: bindiff_export
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import mkstemp [as 別名]
def bindiff_export(self, sample, is_64_bit = True, timeout = None):
"""
Load a sample into IDA Pro, perform autoanalysis and export a BinDiff database.
:param sample: The sample's path
:param is_64_bit: If the sample needs to be analyzed by the 64 bit version of IDA
:param timeout: Timeout for the analysis in seconds
:return: The file name of the exported bindiff database. The file needs
to be deleted by the caller. Returns None on error.
"""
data_to_send = {
"timeout": timeout,
"is_64_bit": is_64_bit}
url = "%s/binexport" % next(self._urls)
log.debug("curl -XPOST --data '%s' '%s'", json.dumps(data_to_send), url)
response = requests.post(url, data = data_to_send, files = {os.path.basename(sample): open(sample, "rb")})
if response.status_code == 200:
handle, output = tempfile.mkstemp(suffix = ".BinExport")
with os.fdopen(handle, "wb") as f:
map(f.write, response.iter_content(1024))
return output
else:
log.error("Bindiff server responded with status code %d: %s", response.status_code, response.content)
return None
示例3: pickle_export
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import mkstemp [as 別名]
def pickle_export(self, sample, is_64_bit = True, timeout = None):
"""
Load a sample into IDA Pro, perform autoanalysis and export a pickle file.
:param sample: The sample's path
:param is_64_bit: If the sample needs to be analyzed by the 64 bit version of IDA
:param timeout: Timeout for the analysis in seconds
:return: The file name of the exported pickle database. The file needs
to be deleted by the caller. Returns None on error.
"""
data_to_send = {
"timeout": timeout,
"is_64_bit": is_64_bit}
url = "%s/pickle" % next(self._urls)
log.debug("curl -XPOST --data '%s' '%s'", json.dumps(data_to_send), url)
response = requests.post(url, data = data_to_send, files = {os.path.basename(sample): open(sample, "rb")})
if response.status_code == 200:
handle, output = tempfile.mkstemp(suffix = ".pickle")
with os.fdopen(handle, "wb") as f:
map(f.write, response.iter_content(1024))
return output
else:
log.error("Bindiff server responded with status code %d: %s", response.status_code, response.content)
return None
示例4: compare
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import mkstemp [as 別名]
def compare(self, primary, secondary, timeout = None):
"""
Run BinDiff on the two BinDiff databases.
:param primary: The first BinExport database
:param secondary: The second BinExport database
:param timeout: Timeout for the command in seconds
:returns: The directory name of the directory with the generated data on the shared volume
"""
url = "%s/compare" % next(self._urls)
log.debug("curl -XPOST --form 'timeout=%s' --form 'primary=@%s' --form 'secondary=@%s' '%s'", str(timeout), primary, secondary, url)
response = requests.post(url, data = {"timeout": timeout}, \
files = {"primary": open(primary, "rb"), "secondary": open(secondary, "rb")})
if response.status_code == 200:
handle, path = tempfile.mkstemp(suffix = ".bindiff.sqlite3")
with os.fdopen(handle, "wb") as f:
map(f.write, response.iter_content(1024))
return path
else:
log.error("Bindiff server responded with status code %d: %s", response.status_code, response.content)
return None
示例5: whitelist_add
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import mkstemp [as 別名]
def whitelist_add():
log.info("whitelist_add called")
try:
file_ = request.files["file"]
handle, filename = tempfile.mkstemp()
os.close(handle)
file_.save(filename)
data = request.get_json()
if data and "functions" in data:
functions = data["functions"]
else:
functions = None
bass.whitelist_add(filename, functions)
os.unlink(filename)
except KeyError:
log.exception("")
return make_response(jsonify(message = "Sample file 'file' missing in POST request"), 400)
return jsonify(message = "OK")
示例6: _symbolize
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import mkstemp [as 別名]
def _symbolize(target, output, tool, exp_opt):
fd, tmp_log = tempfile.mkstemp(prefix="%s_log" % tool, suffix=".txt", dir=".")
try:
os.write(fd, output)
finally:
os.close(fd)
try:
result = _common.run([TOOL_GDB, "-batch", "-nx",
"-ex", "set python print-stack full",
"-ex", "py import exploitable",
"-ex", "exploitable -m %s %s" % (exp_opt, tmp_log),
"-ex", "quit", target], timeout=180)
finally:
_common.delete(tmp_log)
if result.classification == _common.TIMEOUT:
raise RuntimeError("Timed out while processing %s output:\n%s" % (tool, output))
result.backtrace, result.classification = _process_gdb_output(result.text)
result.text = _common._limit_output_length(result.text)
if result.classification == _common.NOT_AN_EXCEPTION:
raise RuntimeError("Failed to process %s output:\n%s" % (tool, output))
return result
示例7: testGenerateFiles
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import mkstemp [as 別名]
def testGenerateFiles(self):
tmp_dir = self.get_temp_dir()
(_, tmp_file_path) = tempfile.mkstemp(dir=tmp_dir)
tmp_file_name = os.path.basename(tmp_file_path)
# Generate a trivial file and assert the file exists.
def test_generator():
yield {"inputs": [1], "target": [1]}
filenames = generator_utils.train_data_filenames(tmp_file_name, tmp_dir, 1)
generator_utils.generate_files(test_generator(), filenames)
self.assertTrue(tf.gfile.Exists(tmp_file_path + "-train-00000-of-00001"))
# Clean up.
os.remove(tmp_file_path + "-train-00000-of-00001")
os.remove(tmp_file_path)
示例8: testGunzipFile
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import mkstemp [as 別名]
def testGunzipFile(self):
tmp_dir = self.get_temp_dir()
(_, tmp_file_path) = tempfile.mkstemp(dir=tmp_dir)
# Create a test zip file and unzip it.
with gzip.open(tmp_file_path + ".gz", "wb") as gz_file:
gz_file.write(bytes("test line", "utf-8"))
generator_utils.gunzip_file(tmp_file_path + ".gz", tmp_file_path + ".txt")
# Check that the unzipped result is as expected.
lines = []
for line in io.open(tmp_file_path + ".txt", "rb"):
lines.append(line.decode("utf-8").strip())
self.assertEqual(len(lines), 1)
self.assertEqual(lines[0], "test line")
# Clean up.
os.remove(tmp_file_path + ".gz")
os.remove(tmp_file_path + ".txt")
os.remove(tmp_file_path)
示例9: open_media
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import mkstemp [as 別名]
def open_media(scr, epub, src):
sfx = os.path.splitext(src)[1]
fd, path = tempfile.mkstemp(suffix=sfx)
try:
with os.fdopen(fd, "wb") as tmp:
tmp.write(epub.file.read(src))
# run(VWR +" "+ path, shell=True)
subprocess.call(
VWR + [path],
# shell=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
k = scr.getch()
finally:
os.remove(path)
return k
示例10: download
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import mkstemp [as 別名]
def download(directory, filename):
"""Download (and unzip) a file from the MNIST dataset if not already done."""
filepath = os.path.join(directory, filename)
if tf.gfile.Exists(filepath):
return filepath
if not tf.gfile.Exists(directory):
tf.gfile.MakeDirs(directory)
# CVDF mirror of http://yann.lecun.com/exdb/mnist/
url = 'https://storage.googleapis.com/cvdf-datasets/mnist/' + filename + '.gz'
_, zipped_filepath = tempfile.mkstemp(suffix='.gz')
print('Downloading %s to %s' % (url, zipped_filepath))
urllib.request.urlretrieve(url, zipped_filepath)
with gzip.open(zipped_filepath, 'rb') as f_in, \
tf.gfile.Open(filepath, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
os.remove(zipped_filepath)
return filepath
示例11: set
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import mkstemp [as 別名]
def set(self, key, value, timeout=None):
if timeout is None:
timeout = self.default_timeout
filename = self._get_filename(key)
self._prune()
try:
fd, tmp = tempfile.mkstemp(suffix=self._fs_transaction_suffix,
dir=self._path)
f = os.fdopen(fd, 'wb')
try:
pickle.dump(int(time() + timeout), f, 1)
pickle.dump(value, f, pickle.HIGHEST_PROTOCOL)
finally:
f.close()
rename(tmp, filename)
os.chmod(filename, self._mode)
except (IOError, OSError):
pass
示例12: put
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import mkstemp [as 別名]
def put(self, key, sync_object, callback=None):
path = os.path.join(self.path, key)
self.ensure_path(path)
BUFFER_SIZE = 4096
fd, temp_path = tempfile.mkstemp()
try:
with open(temp_path, "wb") as fp_1:
while True:
data = sync_object.fp.read(BUFFER_SIZE)
fp_1.write(data)
if callback is not None:
callback(len(data))
if len(data) < BUFFER_SIZE:
break
shutil.move(temp_path, path)
except Exception:
os.remove(temp_path)
raise
finally:
os.close(fd)
self.set_remote_timestamp(key, sync_object.timestamp)
示例13: cache_to_tempfile
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import mkstemp [as 別名]
def cache_to_tempfile(cls, sequence, delete_on_gc=True):
"""
Write the given sequence to a temporary file as a pickle
corpus; and then return a ``PickleCorpusView`` view for that
temporary corpus file.
:param delete_on_gc: If true, then the temporary file will be
deleted whenever this object gets garbage-collected.
"""
try:
fd, output_file_name = tempfile.mkstemp('.pcv', 'nltk-')
output_file = os.fdopen(fd, 'wb')
cls.write(sequence, output_file)
output_file.close()
return PickleCorpusView(output_file_name, delete_on_gc)
except (OSError, IOError) as e:
raise ValueError('Error while creating temp file: %s' % e)
######################################################################
#{ Block Readers
######################################################################
示例14: dump
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import mkstemp [as 別名]
def dump(self, filename=None):
"""
Save a pickle dump of the crashing object on filename.
If filename is None, the crash dump is saved on a file created by
the tempfile module.
Return the filename.
"""
if filename is None:
# This 'temporary file' should actually stay 'forever', i.e. until
# deleted by the user.
(fd, filename)=_tempfile.mkstemp(suffix=".pic", prefix="MDPcrash_")
fl = _os.fdopen(fd, 'w+b', -1)
else:
fl = open(filename, 'w+b', -1)
_cPickle.dump(self.crashing_obj, fl)
fl.close()
return filename
示例15: showTempPDF
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import mkstemp [as 別名]
def showTempPDF(pdfData, cfgGl, mainFrame):
try:
try:
util.removeTempFiles(misc.tmpPrefix)
fd, filename = tempfile.mkstemp(prefix = misc.tmpPrefix,
suffix = ".pdf")
try:
os.write(fd, pdfData)
finally:
os.close(fd)
util.showPDF(filename, cfgGl, mainFrame)
except IOError, (errno, strerror):
raise MiscError("IOError: %s" % strerror)
except TrelbyError, e:
wx.MessageBox("Error writing temporary PDF file: %s" % e,
"Error", wx.OK, mainFrame)