[Tutor] Closing handles (was valueOf() equivalent)

Michael P. Reilly arcege@shore.net
Fri, 22 Dec 2000 11:56:48 -0500 (EST)


> 
> D-Man wrote:
> 
> > In any case it's still good practice to explicitly close all file handles and
> > network connections before exiting.
> 
> Ok so, uh, how do I close a connection that has been opened with 
> 'os.popen()'?
> 
> I was reasonably confident that Python would close the connection for me 
> but I always try to close anything I open in my code just to be sure.

There is another value of closing a popen'd connection.  Every program
has an "exit status" code, which is sometimes very useful.  This exit
code is retrieved (as per os.wait) when you close the returned file
object.

>>> f = os.popen('finger %s@localhost' % username, 'r')
>>> finger_output = f.read()
>>> status = f.close()
>>> if status is not None:  # close() (and the related wait()) returns
...                         # None instead of the usual 0
...
>>>     # the finger failed
>>>     raise SystemError( "finger failed", os.WEXITSTATUS(status) )

Then you can use the os.WEXITSTATUS, os.WIFEXITED, os.WIFSIGNALED,
os.WIFSTOPPED, os.WSTOPSIG and os.WTERMSIG functions. 

There are other issues (specifically relating to UNIX systems) but
those are just details and shouldn't matter that much for basic
operations.

  -Arcege

References:
1.  Python Language Reference, section 6.1.2 File Object Creation
    <URL: http://www.python.org/doc/current/lib/os-newstreams.html>
2.  Python Language Reference, section 6.1.5 Process Management
    <URL: http://www.python.org/doc/current/lib/os-process.html>

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------