本文整理汇总了Python中tempfile.TemporaryFile方法的典型用法代码示例。如果您正苦于以下问题:Python tempfile.TemporaryFile方法的具体用法?Python tempfile.TemporaryFile怎么用?Python tempfile.TemporaryFile使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tempfile
的用法示例。
在下文中一共展示了tempfile.TemporaryFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setUp
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryFile [as 别名]
def setUp(self):
file_path = resource_filename(Requirement.parse('google_streetview'), 'google_streetview/config.json')
with open(file_path, 'r') as in_file:
defaults = json.load(in_file)
params = [{
'size': '600x300', # max 640x640 pixels
'location': '46.414382,10.013988',
'heading': '151.78',
'pitch': '-0.76',
'key': defaults['key']
}]
self.results = google_streetview.api.results(params)
tempfile = TemporaryFile()
self.tempfile = str(tempfile.name)
tempfile.close()
self.tempdir = str(TemporaryDirectory().name)
示例2: create
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryFile [as 别名]
def create(ctx):
"""
Install a chute from the working directory.
"""
url = "{}/chutes/".format(ctx.obj['base_url'])
headers = {'Content-Type': 'application/x-tar'}
if not os.path.exists("paradrop.yaml"):
raise Exception("No paradrop.yaml file found in working directory.")
with tempfile.TemporaryFile() as temp:
tar = tarfile.open(fileobj=temp, mode="w")
for dirName, subdirList, fileList in os.walk('.'):
for fname in fileList:
path = os.path.join(dirName, fname)
arcname = os.path.normpath(path)
tar.add(path, arcname=arcname)
tar.close()
temp.seek(0)
res = router_request("POST", url, headers=headers, data=temp)
data = res.json()
ctx.invoke(watch, change_id=data['change_id'])
示例3: update
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryFile [as 别名]
def update(ctx):
"""
Update the chute from the working directory.
"""
url = ctx.obj['chute_url']
headers = {'Content-Type': 'application/x-tar'}
if not os.path.exists("paradrop.yaml"):
raise Exception("No paradrop.yaml file found in working directory.")
with tempfile.TemporaryFile() as temp:
tar = tarfile.open(fileobj=temp, mode="w")
for dirName, subdirList, fileList in os.walk('.'):
for fname in fileList:
path = os.path.join(dirName, fname)
arcname = os.path.normpath(path)
tar.add(path, arcname=arcname)
tar.close()
temp.seek(0)
res = router_request("PUT", url, headers=headers, data=temp)
data = res.json()
ctx.invoke(watch, change_id=data['change_id'])
示例4: redirect_output
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryFile [as 别名]
def redirect_output(self, statement):
if statement.parsed.pipeTo:
self.kept_state = Statekeeper(self, ('stdout',))
self.kept_sys = Statekeeper(sys, ('stdout',))
self.redirect = subprocess.Popen(statement.parsed.pipeTo, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
sys.stdout = self.stdout = self.redirect.stdin
elif statement.parsed.output:
if (not statement.parsed.outputTo) and (not can_clip):
raise EnvironmentError('Cannot redirect to paste buffer; install ``xclip`` and re-run to enable')
self.kept_state = Statekeeper(self, ('stdout',))
self.kept_sys = Statekeeper(sys, ('stdout',))
if statement.parsed.outputTo:
mode = 'w'
if statement.parsed.output == 2 * self.redirector:
mode = 'a'
sys.stdout = self.stdout = open(os.path.expanduser(statement.parsed.outputTo), mode)
else:
sys.stdout = self.stdout = tempfile.TemporaryFile(mode="w+")
if statement.parsed.output == '>>':
self.stdout.write(get_paste_buffer())
示例5: test_library_location
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryFile [as 别名]
def test_library_location():
from fusesoc.main import _get_core, init_coremanager
tcf = tempfile.TemporaryFile(mode="w+")
tcf.write(
EXAMPLE_CONFIG.format(
build_root=build_root,
cache_root=cache_root,
cores_root=cores_root,
library_root=library_root,
auto_sync="false",
sync_uri=sync_uri,
sync_type="git",
)
)
tcf.seek(0)
conf = Config(file=tcf)
cm = init_coremanager(conf, [])
_get_core(cm, "mor1kx-generic")
_get_core(cm, "atlys")
示例6: __init__
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryFile [as 别名]
def __init__(self, targetfd, tmpfile=None, now=True, patchsys=False):
""" save targetfd descriptor, and open a new
temporary file there. If no tmpfile is
specified a tempfile.Tempfile() will be opened
in text mode.
"""
self.targetfd = targetfd
if tmpfile is None and targetfd != 0:
f = tempfile.TemporaryFile('wb+')
tmpfile = dupfile(f, encoding="UTF-8")
f.close()
self.tmpfile = tmpfile
self._savefd = os.dup(self.targetfd)
if patchsys:
self._oldsys = getattr(sys, patchsysdict[targetfd])
if now:
self.start()
示例7: capture
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryFile [as 别名]
def capture(self, data, term_instance=None):
"""
Stores *data* as a temporary file and returns that file's object.
*term_instance* can be used by overrides of this function to make
adjustments to the terminal emulator after the *data* is captured e.g.
to make room for an image.
"""
# Remove the extra \r's that the terminal adds:
data = data.replace(b'\r\n', b'\n')
logging.debug("capture() len(data): %s" % len(data))
# Write the data to disk in a temporary location
self.file_obj = tempfile.TemporaryFile()
self.file_obj.write(data)
self.file_obj.flush()
# Leave it open
return self.file_obj
示例8: test_exec_command_stdout
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryFile [as 别名]
def test_exec_command_stdout():
# Regression test for gh-2999 and gh-2915.
# There are several packages (nose, scipy.weave.inline, Sage inline
# Fortran) that replace stdout, in which case it doesn't have a fileno
# method. This is tested here, with a do-nothing command that fails if the
# presence of fileno() is assumed in exec_command.
# The code has a special case for posix systems, so if we are on posix test
# both that the special case works and that the generic code works.
# Test posix version:
with redirect_stdout(StringIO()):
with redirect_stderr(TemporaryFile()):
exec_command.exec_command("cd '.'")
if os.name == 'posix':
# Test general (non-posix) version:
with emulate_nonposix():
with redirect_stdout(StringIO()):
with redirect_stderr(TemporaryFile()):
exec_command.exec_command("cd '.'")
示例9: annotation_stream
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryFile [as 别名]
def annotation_stream(self, with_checksum=False):
# create a large temporary file
f = tempfile.TemporaryFile()
for _ in range(5000):
f.write(b"1234567890!" * 1000)
filesize = f.tell()
f.seek(os.SEEK_SET, 0)
# return the file data via annotation stream (remote iterator)
annotation_size = 500000
print("transmitting file via annotations stream (%d bytes in chunks of %d)..." % (filesize, annotation_size))
with f:
while True:
chunk = f.read(annotation_size)
if not chunk:
break
# store the file data chunk in the FDAT response annotation,
# and return the current file position and checksum (if asked).
current_context.response_annotations = {"FDAT": chunk}
yield f.tell(), zlib.crc32(chunk) if with_checksum else 0
示例10: _makefile
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryFile [as 别名]
def _makefile(self):
import tempfile
import mmap
if self.size == 0:
return bytearray()
# posix version
if self.location is None or not os.path.exists(self.location):
if self.location is None:
fd = tempfile.TemporaryFile()
self.blocks = set()
else:
fd = io.open(self.location, "wb+")
fd.seek(self.size - 1)
fd.write(b"1")
fd.flush()
else:
fd = io.open(self.location, "rb+")
return mmap.mmap(fd.fileno(), self.size)
示例11: check_for_writable_imgdir
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryFile [as 别名]
def check_for_writable_imgdir():
c.debug("Testing write perms by creating tempfile in {}".format(cfg.opts.img_dir))
try:
f = tempfile.TemporaryFile(dir=cfg.opts.img_dir)
f.close()
except:
dirstat = os.stat(cfg.opts.img_dir)
user = pwd.getpwuid(dirstat.st_uid).pw_name
group = grp.getgrgid(dirstat.st_gid).gr_name
print(c.RED("Unable to create new file in image dir '{}' owned by {}:{}".format(cfg.opts.img_dir, user, group)))
if myUser in grp.getgrnam(group).gr_mem:
print("Your user ({}) *is* a member of the appropriate group ({}); however ...\n"
"Your current login session is not running with that group credential\n"
"To fix this, open a new session (ssh/su -) or log out & log back in (GUI)".format(myUser, group))
else:
print("Either fix directory permissions as root or specify alternate dir with '--img-dir' option")
exit(1)
示例12: __init__
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryFile [as 别名]
def __init__(self, targetfd, tmpfile=None):
self.targetfd = targetfd
try:
self.targetfd_save = os.dup(self.targetfd)
except OSError:
self.start = lambda: None
self.done = lambda: None
else:
if targetfd == 0:
assert not tmpfile, "cannot set tmpfile with stdin"
tmpfile = open(os.devnull, "r")
self.syscapture = SysCapture(targetfd)
else:
if tmpfile is None:
f = TemporaryFile()
with f:
tmpfile = safe_text_dupfile(f, mode="wb+")
if targetfd in patchsysdict:
self.syscapture = SysCapture(targetfd, tmpfile)
else:
self.syscapture = NoCapture()
self.tmpfile = tmpfile
self.tmpfile_fd = tmpfile.fileno()
示例13: pytest_configure
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryFile [as 别名]
def pytest_configure(config):
if config.option.pastebin == "all":
tr = config.pluginmanager.getplugin("terminalreporter")
# if no terminal reporter plugin is present, nothing we can do here;
# this can happen when this function executes in a slave node
# when using pytest-xdist, for example
if tr is not None:
# pastebin file will be utf-8 encoded binary file
config._pastebinfile = tempfile.TemporaryFile("w+b")
oldwrite = tr._tw.write
def tee_write(s, **kwargs):
oldwrite(s, **kwargs)
if isinstance(s, str):
s = s.encode("utf-8")
config._pastebinfile.write(s)
tr._tw.write = tee_write
示例14: test_no_out_encoding
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryFile [as 别名]
def test_no_out_encoding(self):
"""test redirection of stdout with non ascii caracters
"""
# This test reproduces bug #48066 ; it happens when stdout is redirected
# through '>' : the sys.stdout.encoding becomes then None, and if the
# output contains non ascii, pylint will crash
if sys.version_info < (3, 0):
strio = tempfile.TemporaryFile()
else:
strio = StringIO()
assert strio.encoding is None
self._runtest(
[join(HERE, "regrtest_data/no_stdout_encoding.py"), "--enable=all"],
out=strio,
code=28,
)
示例15: __init__
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryFile [as 别名]
def __init__(self, cloud_provider, rule_dirs=None, rule_filename=None, rule_args=None, rule_level='danger'):
super().__init__(cloud_provider)
rule_dirs = [] if rule_dirs is None else rule_dirs
rule_args = [] if rule_args is None else rule_args
self.rule_type = 'findings'
tmp_ruleset = {'rules': {}, 'about': 'Temporary, single-rule ruleset.'}
tmp_ruleset['rules'][rule_filename] = []
rule = {'enabled': True, 'level': rule_level}
if len(rule_args):
rule['args'] = rule_args
tmp_ruleset['rules'][rule_filename].append(rule)
tmp_ruleset_file = tempfile.TemporaryFile('w+t')
tmp_ruleset_file.write(json.dumps(tmp_ruleset))
self.rules_data_path = os.path.dirname(
os.path.dirname(os.path.abspath(__file__))) + '/providers/%s/rules' % cloud_provider
self.load_rules(file=tmp_ruleset_file, rule_type='findings')
self.shared_init(False, rule_dirs, '', [])