[Tutor] How to discover which OS my python is running?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Nov 23 21:47:03 CET 2005


On Wed, 23 Nov 2005, Kent Johnson wrote:

> Diego Galho Prestes wrote:

> > Hi! I'm using a program that I want to know if I'm running the program
> > in Linux or Windows. How can I do this? I want this because I created
> > all my program in Linux but if someone runs it in Windows I have to do
> > some things to make it work well, and I want to do this verification
> > automatically.
>
> Try sys.platform or os.name.


Hi Diego,

Yes, even Distutils takes this approach.  We can take a look at the
function get_platform_lib(), where they use os.name to figure out what
platform the program is running under.

    http://svn.python.org/projects/python/trunk/Lib/distutils/sysconfig.py

(Hey, I didn't realize that python.org moved their source code repository
from CVS to Subversion!  When did this happen?!  Oh, ok, I see the PEP
now.  http://www.python.org/peps/pep-0347.html.  Cool!)

Sorry, got off track.  Anyway, Distutils appears to do a fairly simple
case analysis:

######
    if os.name == "posix":
        ## text cut
    elif os.name == "nt":
        ## text cut
    elif os.name == "mac":
        ## text cut
    elif os.name == "os2":
        ## text cut
######

So if it's good enough for Distutils, it may work out for you.  *grin*

You may want to isolate whatever platform-dependent parts of your
application you have off to a separate module.  That is, if you can, try
writing modules that hide away the platform ugliness, so that the rest of
your application can behave as if everything were platform-independent.

Best of wishes to you!



More information about the Tutor mailing list