本文整理汇总了Python中os.fdopen方法的典型用法代码示例。如果您正苦于以下问题:Python os.fdopen方法的具体用法?Python os.fdopen怎么用?Python os.fdopen使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.fdopen方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_num_triggering_samples
# 需要导入模块: import os [as 别名]
# 或者: from os import fdopen [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 os [as 别名]
# 或者: from os import fdopen [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 os [as 别名]
# 或者: from os import fdopen [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 os [as 别名]
# 或者: from os import fdopen [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: open_media
# 需要导入模块: import os [as 别名]
# 或者: from os import fdopen [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
示例6: set
# 需要导入模块: import os [as 别名]
# 或者: from os import fdopen [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
示例7: cache_to_tempfile
# 需要导入模块: import os [as 别名]
# 或者: from os import fdopen [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
######################################################################
示例8: dump
# 需要导入模块: import os [as 别名]
# 或者: from os import fdopen [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
示例9: run_py
# 需要导入模块: import os [as 别名]
# 或者: from os import fdopen [as 别名]
def run_py(executable, *code):
"""Run the given python code with the given executable."""
if os.name == 'nt' and len(code) > 1:
# Windows can't do newlines in arguments...
oshandle, filename = tempfile.mkstemp()
with os.fdopen(oshandle, 'w') as f:
f.write('\n'.join(code))
cmd = [executable, filename]
try:
ret = subprocess.run(cmd, universal_newlines=True, check=True,
stdout=subprocess.PIPE).stdout
finally:
os.remove(filename)
else:
cmd = [executable, '-c', '\n'.join(code)]
ret = subprocess.run(cmd, universal_newlines=True, check=True,
stdout=subprocess.PIPE).stdout
return ret.rstrip()
示例10: write_pid_to_pidfile
# 需要导入模块: import os [as 别名]
# 或者: from os import fdopen [as 别名]
def write_pid_to_pidfile(pidfile_path):
""" Write the PID in the named PID file.
Get the numeric process ID (“PID”) of the current process
and write it to the named file as a line of text.
"""
open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
open_mode = 0o644
pidfile_fd = os.open(pidfile_path, open_flags, open_mode)
pidfile = os.fdopen(pidfile_fd, 'w')
# According to the FHS 2.3 section on PID files in /var/run:
#
# The file must consist of the process identifier in
# ASCII-encoded decimal, followed by a newline character. For
# example, if crond was process number 25, /var/run/crond.pid
# would contain three characters: two, five, and newline.
pid = os.getpid()
pidfile.write("%s\n" % pid)
pidfile.close()
示例11: __run
# 需要导入模块: import os [as 别名]
# 或者: from os import fdopen [as 别名]
def __run(self):
"""Runs vulture"""
errTmp = tempfile.mkstemp()
errStream = os.fdopen(errTmp[0])
process = Popen(['vulture', self.__path],
stdin=PIPE,
stdout=PIPE, stderr=errStream)
process.stdin.close()
processStdout = process.stdout.read()
process.stdout.close()
errStream.seek(0)
err = errStream.read()
errStream.close()
process.wait()
try:
os.unlink(errTmp[1])
except:
pass
return processStdout.decode(DEFAULT_ENCODING), err.strip()
示例12: unpackXOR
# 需要导入模块: import os [as 别名]
# 或者: from os import fdopen [as 别名]
def unpackXOR(filename, sig, tempdir=None):
tmpdir = fwunpack.unpacksetup(tempdir)
tmpfile = tempfile.mkstemp(dir=tmpdir)
os.fdopen(tmpfile[0]).close()
fwunpack.unpackFile(filename, 0, tmpfile[1], tmpdir, modify=True)
datafile = open(filename)
datafile.seek(0)
data = datafile.read(1000000)
## read data, XOR, write data out again
f2 = open(tmpfile[1], 'w')
counter = 0
while data != '':
for i in data:
f2.write(chr(ord(i) ^ ord(signatures[sig][counter])))
counter = (counter+1)%len(signatures[sig])
data = datafile.read(1000000)
f2.close()
datafile.close()
return tmpdir
示例13: comparebinaries
# 需要导入模块: import os [as 别名]
# 或者: from os import fdopen [as 别名]
def comparebinaries(path1, path2):
basepath1 = os.path.basename(path1)
dirpath1 = os.path.dirname(path1)
basepath2 = os.path.basename(path2)
dirpath2 = os.path.dirname(path2)
## binaries are identical
if gethash(dirpath1, basepath1) == gethash(dirpath2, basepath2):
return 0
difftmp = tempfile.mkstemp()
os.fdopen(difftmp[0]).close()
p = subprocess.Popen(["bsdiff", path1, path2, difftmp[1]], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
## cleanup
(stanout, stanerr) = p.communicate()
diffsize = os.stat(difftmp[1]).st_size
os.unlink(difftmp[1])
return diffsize
示例14: set
# 需要导入模块: import os [as 别名]
# 或者: from os import fdopen [as 别名]
def set(self, key, value, timeout=None):
if timeout is None:
timeout = int(time() + self.default_timeout)
elif timeout != 0:
timeout = int(time() + timeout)
filename = self._get_filename(key)
self._prune()
try:
fd, tmp = tempfile.mkstemp(suffix=self._fs_transaction_suffix,
dir=self._path)
with os.fdopen(fd, 'wb') as f:
pickle.dump(timeout, f, 1)
pickle.dump(value, f, pickle.HIGHEST_PROTOCOL)
rename(tmp, filename)
os.chmod(filename, self._mode)
except (IOError, OSError):
return False
else:
return True
示例15: __init__
# 需要导入模块: import os [as 别名]
# 或者: from os import fdopen [as 别名]
def __init__(self, cfg):
old_umask = os.umask(cfg.umask)
fdir = cfg.worker_tmp_dir
if fdir and not os.path.isdir(fdir):
raise RuntimeError("%s doesn't exist. Can't create workertmp." % fdir)
fd, name = tempfile.mkstemp(prefix="wgunicorn-", dir=fdir)
# allows the process to write to the file
util.chown(name, cfg.uid, cfg.gid)
os.umask(old_umask)
# unlink the file so we don't leak tempory files
try:
if not IS_CYGWIN:
util.unlink(name)
self._tmp = os.fdopen(fd, 'w+b', 1)
except:
os.close(fd)
raise
self.spinner = 0