python - Python中有没有办法不使用with语句,也不需要手动调用.close?
问题描述
在Python
打开文件时,您应该这样做:
# automatically calls .close method on exit from the with statement
with open("my_file.txt", "r") as f:
...
或这个:
try:
f = open("my_file.txt", "r")
...
except:
...
finally:
f.close()
但是,我想要这样的东西。
f = open("my_file.txt", "r")
# operate with the file
...
# file is not going to be referenced anymore
# or there has been an exception
# close the file but without manually calling the f.close method
我知道垃圾收集器可能会关闭文件,但我想明确地这样做而不手动执行或执行with
语句。
有没有办法使用任何magic
类方法或使用contextlib
库或任何其他库来做到这一点?
用例
我想要这样的原因是因为我在不同httpx.AsyncClient
的python
模块中functions
使用script
. 我不想将httpx.AsyncClient
实例作为参数传递给每个函数,而是在脚本开始时将其定义一次,如果出现故障(异常等),则会自动关闭它。
解决方案
警告
我将保留答案,因为它回答了原始问题。但是任何看到这个的人都应该被警告它不适用于异步。您可以在下面的评论中看到有关此的更多详细信息
使用atexit 模块可能吗?
import atexit
f = open("my_file.txt", "r")
@atexit.register
def closefile():
f.close()
# operate with the file
# ...
推荐阅读
- html - flex-grow:将最大宽度限制为 100% 减去其他同级项
- selenium - Webdriverio selenium Standalone 不更新驱动程序版本
- python - 如何让用户使用 csv 文件中的数据执行计算?
- c# - AddRelativeForce() 导致不必要的转向
- python - 粘贴而不更改字体
- c# - 如何随机找到从点P切线到球体的向量之一
- react-native - React native 每次打开页面时如何执行功能
- javascript - 将 svg 路径 d 拆分为对象数组
- spring-cloud - 无法在 Spring Cloud Data Flow 中运行组合任务
- stripe-payments - 条纹可以在已保存的卡上存钱吗?