如何解决Python pathlib.unlink: 'str' 对象没有属性 '_accessor' 输出:
我正在尝试使用 Path.unlink 删除 pytest 夹具中的测试文件,但我在拆卸时不断收到此错误。
夹具拆解代码:
yield
try:
for i in range(2):
file = db_helper(f'testfile{i}')
Path.unlink(file)
finally:
file = db_helper('testfile')
Path.unlink(file)
db_helper:
def db_helper(filename):
"""Helper function for generate_db and retrieve_db"""
if name == "posix":
home = getenv('HOME')
path = Path(f'{home}/.local/apikeychain/')
elif name == "nt":
appdata = getenv('APPDATA')
path = Path(str(f'{appdata}/apikeychain/'))
else:
raise NotImplementedError
path.mkdir(parents=True,exist_ok=True)
return f'{path}/{filename}.db'
输出:
FTraceback (most recent call last):
File "/home/ctrenthem/api-keychain/tests/conftest.py",line 17,in tmp_keychain
Path.unlink(file)
File "/usr/lib/python3.9/pathlib.py",line 1344,in unlink
self._accessor.unlink(self)
AttributeError: 'str' object has no attribute '_accessor'
During handling of the above exception,another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.9/runpy.py",line 197,in _run_module_as_main
return _run_code(code,main_globals,None,File "/usr/lib/python3.9/runpy.py",line 87,in _run_code
exec(code,run_globals)
<snip>
File "/home/ctrenthem/.cache/pypoetry/virtualenvs/api-keychain-R4MwVzYJ-py3.9/lib/python3.9/site-packages/_pytest/fixtures.py",line 941,in _teardown_yield_fixture
next(it)
File "/home/ctrenthem/api-keychain/tests/conftest.py",line 20,in unlink
self._accessor.unlink(self)
AttributeError: 'str' object has no attribute '_accessor'
我已经尝试使用 Path(file)、Path.path(file) 和其他几个 Path 函数来转换字符串,但它们中的每一个都给出了类似的 AttributeError。此代码需要成功运行才能正确清理测试,因为如果文件已存在,则部分正在测试的代码会引发错误。
此外,如 db_helper 函数所示,我不能只对文件进行硬编码,因为 db 文件是根据用户系统在特定位置生成的,即使我对这些路径进行了硬编码,我仍然会被卡住我的文件仍然是一个字符串对象
解决方法
代码
f'{path}/{filename}.db'
创建字符串。
你应该使用
path / f'{filename}.db'
获取 Path
对象。
然后你就可以了
file = db_helper('testfile')
file.unlink()
顺便说一句:
你也可以使用
home = Path.home()
path = home / '.local/apikeychain'
或更短
path = Path.home() / '.local/apikeychain'
使代码更简单。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。