How Can I Determine the Operating System with Python?

Peter Hansen peter at engcorp.com
Thu Mar 21 19:11:21 EST 2002


Mark Gash wrote:
> 
>         * Mark Hadfield <m.hadfield at niwa.co.nz> [2002-03-21 14:02 +1200]:
>         > >>> import sys
>         > >>> sys.platform
>         > 'win32'
>         > >>> import os
>         > >>> os.name
>         > 'nt'
> 
>         That's a crude way of determining the platform, because sys.platform
>         depends on the compiler used to compile Python. Yes, even on Windows.
>         But I'm  reasonably sure that the Pythonlabs folks won't change their
>         Windows compiler anytime soon.
> 
>         I'd very much like to have a real way for determining the platform.
>         Anybody wants to write a PEP? :-)
> 
> The only way of defining the os name that I have found is then to examine
> the os.environ .By examining the COMSPEC you will be able to determine a win
> 9X machine opposed to an NT or 2000 machine (comspec for 9X will show
> command.com whereas win32 machines will show cmd.exe).

This, and the other proposals, may be exactly the wrong thing to do,
if you've at all followed Alex Martelli's advice about type checking. 

The approach whereby you check explicitly for a certain environment and
then take certain actions based on that, such as running particular
executables and so on, is very like doing type testing when passed an
object instead of just trying to call methods and catch the exceptions
if the call fails.  It's not good to say "this isn't a File object so
I refuse to try writing to it" when you can say "try writing, but
don't crash if there's no write method".  Simpler, robust, and much 
more flexible if someone wants to send in a non-File object which
fakes it.

For example, rather than checking that os.environ['COMSPEC'] is command.exe
and assuming if it's not you aren't on Win98, one should just check
for the external program needed and if it exists, run it.  If instead
you build in too much "smarts" by doing explicit checking, you'll
end up screwing people who have replaced command.exe with something
more useful, such as might happen with certain replacement shells.
They might not have COMSPEC set to command.exe, but unless you 
really are trying to run the standard Win98 command.exe file, you
don't really care about that.  What you care is whether the action
you are trying to take will work or not.  So try taking the action
and catch any exceptions.

(Yes, there are times when you do need to check explicitly,
but they're probably rarer than one might think.)

-Peter



More information about the Python-list mailing list