最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Is using tempfile.mkstemp()[1] leaks open file handles? - Stack Overflow

programmeradmin1浏览0评论

I'm using tempfile.mkstemp()[1] in some class frequently. I'm doing some operations on the created file and then delete it.

I'm not using context manager with with or smth like that, just using the filename.

Obviously, tempfile.mkstemp() returns a tuple of opened file object and the filename. I'm only using filename and not even accessing file object, of course.

I'm wondering if that is causing leaking open file handler when execution is leaving particular method? Or is file object somehow silently closed?

I'm using tempfile.mkstemp()[1] in some class frequently. I'm doing some operations on the created file and then delete it.

I'm not using context manager with with or smth like that, just using the filename.

Obviously, tempfile.mkstemp() returns a tuple of opened file object and the filename. I'm only using filename and not even accessing file object, of course.

I'm wondering if that is causing leaking open file handler when execution is leaving particular method? Or is file object somehow silently closed?

Share Improve this question asked Jan 29 at 14:19 LetMeSOThat4ULetMeSOThat4U 6,82810 gold badges58 silver badges102 bronze badges 2
  • Why are you asking? Are you just curious or is your program long-running and draining your system of memory? – jsf80238 Commented Jan 29 at 14:57
  • I'm asking because a. leaking resources is bad programming practice and so b. it's unprofessional. – LetMeSOThat4U Commented Jan 29 at 18:38
Add a comment  | 

1 Answer 1

Reset to default 1

Yes, you're leaking file handles.

The handle is a numeric file descriptor. They're not unique and there's no way for the garbage collector to know when the reference is gone, so it can't close the file automatically.

You could use os.fdopen() to create a Python file object that references this handle. When this is closed, the file handle will also be closed. You can use a context manager for this, or let it be closed automatically by GC.

发布评论

评论列表(0)

  1. 暂无评论