用于管理临时文件和目录的上下文管理器。
temporar的Python项目详细描述
用于管理临时文件和目录的上下文管理器。
withtemporary.temp_dir()asd:...withtemporary.temp_file(content='hello')asf:...
安装:
$ pip install temporary
临时目录示例
在进入上下文管理器时创建临时目录,并且 退出时删除:
>>>importtemporary>>>withtemporary.temp_dir()astemp_dir:...asserttemp_dir.is_dir()>>>assertnottemp_dir.exists()
这次让我们将临时目录设为工作目录:
>>>importos>>>withtemporary.temp_dir(make_cwd=True)astemp_dir:...assertstr(temp_dir)==os.getcwd()>>>assertnotstr(temp_dir)==os.getcwd()
后缀、前缀和父目录选项将传递给标准 tempfile.mkdtemp()函数:
>>>withtemporary.temp_dir()asp:...withtemporary.temp_dir(suffix='suf',prefix='pre',parent_dir=p)asd:...assertd.parent==p...assertd.name.startswith('pre')...assertd.name.endswith('suf')
此函数还可以用作装饰器,其in_temp_dir别名为:
>>>@temporary.in_temp_dir()...defmy_function():...assertold_cwd!=os.getcwd()...>>>old_cwd=os.getcwd()>>>my_function()>>>assertold_cwd==os.getcwd()
临时文件示例
在进入上下文管理器和 退出时删除。
>>>importtemporary>>>withtemporary.temp_file()astemp_file:...asserttemp_file.exists()>>>assertnottemp_file.exists()
用户还可以为要填充的文件提供一些内容:
>>>withtemporary.temp_file('hello!')astemp_file:...withtemp_file.open()asf:...assertf.read()=='hello!'
临时文件可以放在自定义目录中:
>>>withtemporary.temp_dir()astemp_dir:...withtemporary.temp_file(parent_dir=temp_dir)astemp_file:...asserttemp_file.parent==temp_dir
如果出于某种原因,用户希望在 退出上下文,也没关系:
>>>withtemporary.temp_file()astemp_file:...temp_file.unlink()