How do I check if I'm running on Windows in Python?

engrmahabub
Mahabubur Rahman
Published on Jan, 18 2024 2 min read 0 comments
image

Using python we can found operation system different way.

Method 1 :
We can found running operation system by using Python os module.

os.name: The name of the operating system dependent module imported. The following names have currently been registered: 'posix', 'nt', 'java'.

In our case, we want to check for 'nt' as os.name output as bellow - 

import os

if os.name == 'nt':

There is also a note on os.name:

See also sys.platform has a finer granularity. os.uname() gives system-dependent version information.

The platform module provides detailed checks for the system’s identity.

Method 2:

Using platform.system we can find the operation system.

 system()        

Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.       

 An empty string is returned if the value cannot be determined.

If that isn't working, maybe try platform.win32_ver and if it doesn't raise an exception, you're on Windows; but I don't know if that's forward compatible to 64-bit, since it has 32 in the name.

win32_ver(release='', version='', csd='', ptype='')        

Get additional version information from the Windows Registry        and return a tuple (version,csd,ptype) referring to version        number, CSD level and OS type (multi/single        processor).

For what it's worth, here's a few of the ways they check for Windows in platform.py:

if sys.platform == 'win32':

try: import win32api
#---------
# Emulation using _winreg (added in Python 2.0) and
# sys.getwindowsversion() (added in Python 2.3)
import _winreg
GetVersionEx = sys.getwindowsversion
#----------
if sys.platform == 'win32':
#---------
if os.environ.get('OS','') == 'Windows_NT':
#---------
try: import win32api
#---------
# Emulation using _winreg (added in Python 2.0) and
# sys.getwindowsversion() (added in Python 2.3)
import _winreg
GetVersionEx = sys.getwindowsversion
#----------
def system():

    """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.    
        An empty string is returned if the value cannot be determined.   
    """
    return uname()[0]

 

 

 

0 Comments