diff options
| author | Michał Górny <mgorny@gentoo.org> | 2022-01-31 22:25:34 +0100 |
|---|---|---|
| committer | Michał Górny <mgorny@gentoo.org> | 2022-02-01 18:35:12 +0100 |
| commit | 7daf4855f58cd79e72196d3a5a0b0a860d782ee7 (patch) | |
| tree | 3a1eff4b9e363eb8c97c51f55fe87fa0090a28cf /cherrypy/process | |
| parent | a7983fe61f7237f2354915437b04295694100372 (diff) | |
| download | cherrypy-git-7daf4855f58cd79e72196d3a5a0b0a860d782ee7.tar.gz | |
Use context managers to close files properly and fix tests on PyPy
Use context managers (`with`) to ensure that all open files are closed
correctly. This resolves resource leaks and test failures with PyPy3.7.
The code prior to this change used four approaches for closing files:
1. Using a context manager (`with` clause).
2. Using a try/finally clause.
3. Closing the file in the same scope (unreliable: file object can leak
on exception).
4. Not closing open files at all.
The last point is a real problem for PyPy since it does not GC
unreachable objects as aggressively as CPython does. While leaving
a function scope on CPython causes the file objects private to it to
be destroyed (and therefore closed), in PyPy they can stay dangling
for some time. When combines with buffered writes, this means that
writes can still remain pending after returning from function.
Using a context manager is a simple, consistent way to ensure that
the file object is closed once it is no longer needed. In turn, this
guarantees that all pending writes will be performed upon function
return and the code won't be hiting race conditions between writing
a file and reading it afterwards.
Diffstat (limited to 'cherrypy/process')
| -rw-r--r-- | cherrypy/process/plugins.py | 3 |
1 files changed, 2 insertions, 1 deletions
diff --git a/cherrypy/process/plugins.py b/cherrypy/process/plugins.py index 2a9952de..e96fb1ce 100644 --- a/cherrypy/process/plugins.py +++ b/cherrypy/process/plugins.py @@ -436,7 +436,8 @@ class PIDFile(SimplePlugin): if self.finalized: self.bus.log('PID %r already written to %r.' % (pid, self.pidfile)) else: - open(self.pidfile, 'wb').write(ntob('%s\n' % pid, 'utf8')) + with open(self.pidfile, 'wb') as f: + f.write(ntob('%s\n' % pid, 'utf8')) self.bus.log('PID %r written to %r.' % (pid, self.pidfile)) self.finalized = True start.priority = 70 |
