[GRASS-dev] os.remove

Glynn Clements glynn at gclements.plus.com
Sat Mar 26 11:21:03 PDT 2016


Paulo van Breugel wrote:

> > In the addon r.forestfrag (python script), I used os.remove() to 
> > remove some temporary files (in lines 230, 258 and 430). However, this 
> > fails in Windows, with an error message like below:
> >
> > WindowsError: [Error 32] The process cannot access the file because it 
> > is being used by another process: 
> > 'c:\\users\\uqdshana\\appdata\\local\\temp\\tmpwlv54l'
> >
> > Removing these lines with os.remove() solves the problem, but than the 
> > user is left with these temporary files. Is there a Window compatible 
> > way to remove them in the script?
> 
> Perhaps I should have looked harder first, the underlying problem 
> (described here: https://www.logilab.org/blogentry/17873) seems to be 
> that the file needs to be closed at OS level, which can be done using 
> os.close().

Ideally, files should be handled using context managers and "with".

Python's own file objects are already context managers, so you can use
e.g.

	with open(filename) as f:
	    data = f.read()
	# by this point, f has already been closed

For dealing with OS-level descriptors, you can use contextlib (Python
2.5+) to easily create context managers, e.g.

        import os
        import tempfile
        from contextlib import contextmanager
        
        @contextmanager
        def temp():
            fd, filename = tempfile.mkstemp()
            try:
                yield (fd, filename)
            finally:
                os.close(fd)
                os.remove(filename)

	if __name__ == '__main__':	...
	    with temp() as (fd, filename):
	        whatever()
	    # fd has been closed and the file removed

Use of "with" ensures that clean-up happens in the event of an
exception or other forms of early exit (e.g. return, break, continue).

-- 
Glynn Clements <glynn at gclements.plus.com>


More information about the grass-dev mailing list