if you want POSIX, import posix, not os

Charles G Waldman cgw at fnal.gov
Tue Aug 17 09:48:56 CEST 1999


Dan Connolly writes:
 > I have thought this was broken for years, but I just read
 > it again tonight, and I'm not going to pass over it in silence this
 > time:
 > 
 > "Do not import this module directly. Instead, import the module os,
 > which provides a portable version of this interface."
 > 	-- http://www.python.org/doc/1.5.2p1/lib/module-posix.html
 > 
 > I think this is terrible advice.

I think it's good advice.  If you're not using features like
"getpgrp", but more mundane things like "listdir", then 

import os
files=os.listdir(os.getcwd())

is highly portable (across Mac, Win, and Unix) whereas if you spelled
it

import posix
files=posix.listdir(posix.getcwd())

you'd be introducing a needlessly non-portable construction in your
code.

It's up to you to read the documentation to know what are the
"generic" (always-available) operating system services and which ones
are platform-specific.  The "getpgrp" example you cite is one of the
latter...  if you use it, you  won't be able to get your code to run
on non-Unix platforms.  You have to resort to things like:

import os
if os.name = 'posix':
   pgrp = os.getpgrp()
else:
   #something completely different


 > The os module is *not* portable:
 > 
 > "getpgrp () 
 >     Return the current process group id. Availability: Unix. "
 > 	-- http://www.python.org/doc/1.5.2p1/lib/os-procinfo.html

As the "Availability" comment implies, the os module implements a core 
set of functions, on top of which there are platform-specific
extensions.  If you're not on the right platform, you don't get the
extensions.

 > A portable interface is one where I can expect consistent behaviour
 > of named objects across platforms, no?

Modulo the restrictions of "Availability"

 > The IEEE POSIX spec is widely implemented and understood.
 > When a program expects behaviour as specified in the POSIX
 > specs, it should say
 > 	import posix

If you make heavy use of the posix features this may make sense.  If
all you really need is things like listdir, getcwd, then it's
overkill.

 > It would have made sense for python to define a really portable os
 > module, i.e. the least common denominator of the platforms it
 > runs on. But that's not what we've got.

No reason you can't create an "generic_os" module something like this:

----generic_os.py-----
from os import listdir,getcwd,path,name,remove,....
----------------------

replacing "...." with the list of all functions which are supported on
ALL OS's where Python runs (or all OS's you care about).  A python
program which only imports "generic_os" and not "os" will be highly
portable, and also highly constrained in what it can do.

 > I hope the os module will be deprecated in future releases.

I don't think there is much chance of this happening, it it too widely 
used.






More information about the Python-list mailing list