本文整理汇总了Python中tempfile.TemporaryDirectory方法的典型用法代码示例。如果您正苦于以下问题:Python tempfile.TemporaryDirectory方法的具体用法?Python tempfile.TemporaryDirectory怎么用?Python tempfile.TemporaryDirectory使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tempfile
的用法示例。
在下文中一共展示了tempfile.TemporaryDirectory方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryDirectory [as 别名]
def save(self, path=None):
"""Save model to a pickle located at `path`"""
if path is None:
path = os.path.join(logger.get_dir(), "model.pkl")
with tempfile.TemporaryDirectory() as td:
save_state(os.path.join(td, "model"))
arc_name = os.path.join(td, "packed.zip")
with zipfile.ZipFile(arc_name, 'w') as zipf:
for root, dirs, files in os.walk(td):
for fname in files:
file_path = os.path.join(root, fname)
if file_path != arc_name:
zipf.write(file_path, os.path.relpath(file_path, td))
with open(arc_name, "rb") as f:
model_data = f.read()
with open(path, "wb") as f:
cloudpickle.dump((model_data, self._act_params), f)
示例2: setUp
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryDirectory [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)
示例3: __init__
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryDirectory [as 别名]
def __init__(self, reduce_memory=False):
if reduce_memory:
self.temp_dir = TemporaryDirectory()
self.working_dir = Path(self.temp_dir.name)
self.document_shelf_filepath = self.working_dir / 'shelf.db'
self.document_shelf = shelve.open(str(self.document_shelf_filepath),
flag='n', protocol=-1)
self.documents = None
else:
self.documents = []
self.document_shelf = None
self.document_shelf_filepath = None
self.temp_dir = None
self.doc_lengths = []
self.doc_cumsum = None
self.cumsum_max = None
self.reduce_memory = reduce_memory
示例4: save_act
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryDirectory [as 别名]
def save_act(self, path=None):
"""Save model to a pickle located at `path`"""
if path is None:
path = os.path.join(logger.get_dir(), "model.pkl")
with tempfile.TemporaryDirectory() as td:
save_state(os.path.join(td, "model"))
arc_name = os.path.join(td, "packed.zip")
with zipfile.ZipFile(arc_name, 'w') as zipf:
for root, dirs, files in os.walk(td):
for fname in files:
file_path = os.path.join(root, fname)
if file_path != arc_name:
zipf.write(file_path, os.path.relpath(file_path, td))
with open(arc_name, "rb") as f:
model_data = f.read()
with open(path, "wb") as f:
cloudpickle.dump((model_data, self._act_params), f)
示例5: test_styletransfer_size
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryDirectory [as 别名]
def test_styletransfer_size():
"""Style transfer works for varying image sizes, producing correctly scaled images"""
for alg in ALGORITHMS.keys():
for size in [50, 100, 200]:
for img in ["docker.png", "obama.jpg"]:
originalshape = shape(CONTENTS + img)
tmpdir = TemporaryDirectory()
styletransfer([CONTENTS + img], [STYLES + "cubism.jpg"], tmpdir.name, alg=alg, size=size)
files = glob(tmpdir.name + "/" + filename(img) + "*cubism*")
resultshape = shape(files[0])
rescalefactor = size / originalshape[0]
expectedshape = [size, int(rescalefactor * originalshape[1])]
print("Expected shape", expectedshape)
print("Actual shape", resultshape)
assert len(files) == 1
assert expectedshape == resultshape
示例6: test_reloader_live
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryDirectory [as 别名]
def test_reloader_live(runargs, mode):
with TemporaryDirectory() as tmpdir:
filename = os.path.join(tmpdir, "reloader.py")
text = write_app(filename, **runargs)
proc = Popen(argv[mode], cwd=tmpdir, stdout=PIPE, creationflags=flags)
try:
timeout = Timer(5, terminate, [proc])
timeout.start()
# Python apparently keeps using the old source sometimes if
# we don't sleep before rewrite (pycache timestamp problem?)
sleep(1)
line = scanner(proc)
assert text in next(line)
# Edit source code and try again
text = write_app(filename, **runargs)
assert text in next(line)
finally:
timeout.cancel()
terminate(proc)
with suppress(TimeoutExpired):
proc.wait(timeout=3)
示例7: main
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryDirectory [as 别名]
def main():
random.seed(0)
args = get_arguments()
log.logger = log.Log()
reference, ref_names, circularity, ref_seqs = load_reference(args.reference)
if args.direct:
unpolished_sequences = ref_seqs
else:
unpolished_sequences = build_unpolished_assembly(args, reference, ref_names, ref_seqs)
with tempfile.TemporaryDirectory() as polish_dir:
polishing_rounds(ref_names, unpolished_sequences, circularity, args.reads, args.threads,
polish_dir)
final_assembly = final_shred_and_polish(ref_names, circularity, polish_dir, args.threads)
output_result(final_assembly, circularity)
log.log('')
示例8: setUpClass
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryDirectory [as 别名]
def setUpClass(cls):
# Set db location
file_ = tempfile.NamedTemporaryFile(delete=False)
global_scope['db_file'] = file_.name
# Create a user key
cls.secret_key = str(uuid.uuid4())
cls.enc = global_scope['enc'] = Encryption(cls.secret_key.encode())
# Load config
cls.conf_path = tempfile.TemporaryDirectory()
cls.config = Config(cls.conf_path.name + '/config')
global_scope['conf'] = cls.config
# Create engine
engine = get_engine()
# Create tables and set database session
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
cls.session = Session()
# Populate db
cls.populate_base()
示例9: test_tutorials
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryDirectory [as 别名]
def test_tutorials():
with TemporaryDirectory() as tmp:
tmp_path = Path(tmp)
# Copy tutorial file resources
for f_path in _TUTORIAL_FILES:
src = _TUTORIALS_ROOT / f_path
dest = tmp_path / f_path
dest.parent.mkdir(parents=True, exist_ok=True)
if src.is_dir():
shutil.copytree(src, dest)
else:
shutil.copy(src, dest)
# Emit a test for each notebook
for nb_path in notebooks_in_path(_TUTORIALS_ROOT):
rel_path = nb_path.relative_to(_TUTORIALS_ROOT)
workdir = tmp_path / rel_path.parent
workdir.mkdir(parents=True, exist_ok=True)
description = "Running notebook {}".format(rel_path)
yield attr(description=description)(run_notebook), nb_path, workdir
示例10: download_session_manager_plugin_linux
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryDirectory [as 别名]
def download_session_manager_plugin_linux(target_path, pkg_format="deb"):
assert pkg_format in {"deb", "rpm"}
if pkg_format == "deb":
sm_plugin_key = "plugin/latest/ubuntu_64bit/session-manager-plugin.deb"
else:
sm_plugin_key = "plugin/latest/linux_64bit/session-manager-plugin.rpm"
with tempfile.TemporaryDirectory() as td:
sm_archive_path = os.path.join(td, os.path.basename(sm_plugin_key))
clients.s3.download_file(sm_plugin_bucket, sm_plugin_key, sm_archive_path)
if pkg_format == "deb":
subprocess.check_call(["dpkg", "-x", sm_archive_path, td])
elif pkg_format == "rpm":
command = "rpm2cpio '{}' | cpio --extract --make-directories --directory '{}'"
subprocess.check_call(command.format(sm_archive_path, td), shell=True)
shutil.move(os.path.join(td, "usr/local/sessionmanagerplugin/bin/session-manager-plugin"), target_path)
示例11: sed
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryDirectory [as 别名]
def sed(self, regex, path, right=444):
""" Replace with sed in the roofs
Example: fs.sed('s/init.d\/S/init.d\/K/g', '/etc/init.d/rcK', right=755)
Insecure !! command injection here but regex is not exposed to user input
"""
with tempfile.TemporaryDirectory() as tempdir:
print("Tempdir {}".format(tempdir))
new = tempdir + "/new"
old = tempdir + "/old"
self.get(path, old)
subprocess.check_call("sed '{regex}' {old} > {new}".format(
regex=regex, new=new, old=old), shell=True)
self.put(new, path, right=right)
示例12: format_results
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryDirectory [as 别名]
def format_results(self, results, txtfile_prefix=None):
"""Format the results to txt (standard format for Cityscapes
evaluation).
Args:
results (list): Testing results of the dataset.
txtfile_prefix (str | None): The prefix of txt files. It includes
the file path and the prefix of filename, e.g., "a/b/prefix".
If not specified, a temp file will be created. Default: None.
Returns:
tuple: (result_files, tmp_dir), result_files is a dict containing
the json filepaths, tmp_dir is the temporal directory created
for saving txt/png files when txtfile_prefix is not specified.
"""
assert isinstance(results, list), 'results must be a list'
assert len(results) == len(self), (
'The length of results is not equal to the dataset len: {} != {}'.
format(len(results), len(self)))
assert isinstance(results, list), 'results must be a list'
assert len(results) == len(self), (
'The length of results is not equal to the dataset len: {} != {}'.
format(len(results), len(self)))
if txtfile_prefix is None:
tmp_dir = tempfile.TemporaryDirectory()
txtfile_prefix = osp.join(tmp_dir.name, 'results')
else:
tmp_dir = None
result_files = self.results2txt(results, txtfile_prefix)
return result_files, tmp_dir
示例13: format_results
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryDirectory [as 别名]
def format_results(self, results, jsonfile_prefix=None, **kwargs):
"""Format the results to json (standard format for COCO evaluation).
Args:
results (list[tuple | numpy.ndarray]): Testing results of the
dataset.
jsonfile_prefix (str | None): The prefix of json files. It includes
the file path and the prefix of filename, e.g., "a/b/prefix".
If not specified, a temp file will be created. Default: None.
Returns:
tuple: (result_files, tmp_dir), result_files is a dict containing
the json filepaths, tmp_dir is the temporal directory created
for saving json files when jsonfile_prefix is not specified.
"""
assert isinstance(results, list), 'results must be a list'
assert len(results) == len(self), (
'The length of results is not equal to the dataset len: {} != {}'.
format(len(results), len(self)))
if jsonfile_prefix is None:
tmp_dir = tempfile.TemporaryDirectory()
jsonfile_prefix = osp.join(tmp_dir.name, 'results')
else:
tmp_dir = None
result_files = self.results2json(results, jsonfile_prefix)
return result_files, tmp_dir
示例14: test_save
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryDirectory [as 别名]
def test_save(adapter, audio_data):
""" Test audio saving. """
with TemporaryDirectory() as directory:
path = join(directory, 'ffmpeg-save.mp3')
adapter.save(
path,
audio_data[0],
audio_data[1])
probe = ffmpeg.probe(TEST_AUDIO_DESCRIPTOR)
assert len(probe['streams']) == 1
stream = probe['streams'][0]
assert stream['codec_type'] == 'audio'
assert stream['channels'] == 2
assert stream['duration'] == '10.919184'
示例15: test_separate_to_file
# 需要导入模块: import tempfile [as 别名]
# 或者: from tempfile import TemporaryDirectory [as 别名]
def test_separate_to_file(test_file, configuration, backend):
""" Test file based separation. """
with tf.Session() as sess:
instruments = MODEL_TO_INST[configuration]
separator = Separator(configuration, stft_backend=backend)
name = splitext(basename(test_file))[0]
with TemporaryDirectory() as directory:
separator.separate_to_file(
test_file,
directory)
for instrument in instruments:
assert exists(join(
directory,
'{}/{}.wav'.format(name, instrument)))