Context manager that creates a temporary folder and deletes it after usage. After the suite finishes, the temporary folder and all its files and subfolders will be deleted. Example: with create_temp_folder() as temp_folder: # We have a temporary folder!
(prefix=tempfile.template, suffix='',
parent_folder=None, chmod=None)
| 16 | |
| 17 | @contextlib.contextmanager |
| 18 | def create_temp_folder(prefix=tempfile.template, suffix='', |
| 19 | parent_folder=None, chmod=None): |
| 20 | ''' |
| 21 | Context manager that creates a temporary folder and deletes it after usage. |
| 22 | |
| 23 | After the suite finishes, the temporary folder and all its files and |
| 24 | subfolders will be deleted. |
| 25 | |
| 26 | Example: |
| 27 | |
| 28 | with create_temp_folder() as temp_folder: |
| 29 | |
| 30 | # We have a temporary folder! |
| 31 | assert temp_folder.is_dir() |
| 32 | |
| 33 | # We can create files in it: |
| 34 | (temp_folder / 'my_file').open('w') |
| 35 | |
| 36 | # The suite is finished, now it's all cleaned: |
| 37 | assert not temp_folder.exists() |
| 38 | |
| 39 | Use the `prefix` and `suffix` string arguments to dictate a prefix and/or a |
| 40 | suffix to the temporary folder's name in the filesystem. |
| 41 | |
| 42 | If you'd like to set the permissions of the temporary folder, pass them to |
| 43 | the optional `chmod` argument, like this: |
| 44 | |
| 45 | create_temp_folder(chmod=0o550) |
| 46 | |
| 47 | ''' |
| 48 | temp_folder = pathlib.Path(tempfile.mkdtemp(prefix=prefix, suffix=suffix, |
| 49 | dir=parent_folder)) |
| 50 | try: |
| 51 | if chmod is not None: |
| 52 | temp_folder.chmod(chmod) |
| 53 | yield temp_folder |
| 54 | finally: |
| 55 | shutil.rmtree(str(temp_folder)) |
| 56 | |
| 57 | |
| 58 | class NotInDict: |