Python get windows or linux

Reliably detect Windows in Python

I’m working on a couple of Linux tools and need to prevent installation on Windows, since it depends on FHS and is thus rendered useless on that platform. The platform.platform function comes close but only returns a string. Unfortunately I don’t know what to search for in that string for it to yield a reliable result. Does anyone know what to search for or does anyone know of another function that I’m missing here?

6 Answers 6

>>> import platform >>> platform.system() 'Windows' 

For those that came here looking for a way to detect Cygwin from Python (as opposed to just detecting Windows), here are some example return values from os.name and platform.system on different platforms

OS/build | os.name | platform.system() -------------+---------+----------------------- Win32 native | nt | Windows Win32 cygwin | posix | CYGWIN_NT-5.1* Win64 native | nt | Windows Win64 cygwin | posix | CYGWIN_NT-6.1-WOW64* Linux | posix | Linux 

From this point, how to distinguish between Windows native and Cygwin should be obvious although I’m not convinced this is future proof.

* version numbers are for XP and Win7 respectively, do not rely on them

@JaceBrowning: fair enough, we are probably using different version of Cygwin or Python. This is where the «not-futureproof» note comes in 🙂

@JaceBrowning: which I call «native» in my post. What exactly is your exact output from os.name and platform.system() ?

So that’s exactly what I listed in the table above for the «native» Python builds that go on Windows. No contradiction.

Just worth nothing that the above only works when the python binary used is the cygwin binary and not a native windows one.

On my Windows box, platform.system() returns ‘Windows’ .

However, I’m not sure why you’d bother. If you want to limit the platform it runs on technologically, I’d use a white-list rather than a black-list.

In fact, I wouldn’t do it technologically at all since perhaps the next release of Python may have Win32/Win64 instead of Windows (for black-listing) and *nix instead of Linux (for white-listing).

My advice is to simply state what the requirements are and, if the user chooses to ignore that, that’s their problem. If they ring up saying they got an error message stating «Cannot find FHS» and they admit they’re running on Windows, gently point out to them that it’s not a supported configuration.

Maybe your customers are smart enough to get FHS running under Windows so that your code will work. They’re unlikely to appreciate what they would then consider an arbitrary limitation of your software.

Читайте также:  Linux mint настройки видеокарты

This is a problem faced by software developers every day. Even huge organizations can’t support every single platform and configuration out there.

Источник

Python linux check if windows or linux python

The outputs of this script ran on a few different systems (Linux, Windows, Solaris, MacOS) and architectures (x86, x64, Itanium, power pc, sparc) is available here: https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version e.g. Solaris on sparc gave: or MacOS on M1 Solution 2: I usually use to get the platform. will distinguish between linux, other unixes, and OS X, while is » » for all of them. I found that the window class name for the Dropbox tray icon was DropboxTrayIcon using Autohotkey Window Spy. See also MSDN FindWindow Solution 1: If you want user readable data but still detailed, you can use platform.platform() also has some other useful methods: Here’s a few different possible calls you can make to identify where you are, linux_distribution and dist seem to have gone from recent python versions, so they have a wrapper function here.

Python check if os is windows or linux

python check is os is windows

from sys import platform if platform == "linux" or platform == "linux2": # linux elif platform == "darwin": # OS X elif platform == "win32": # Windows.

Windows — Can python detect which OS is it running under?, It works both on linux as well as windows. FYI: os.uname() will not work on windows, though it works on linux. Platform is generic.

Check if a process is running or not on Windows?

You can not rely on lock files in Linux or Windows. I would just bite the bullet and iterate through all the running programs. I really do not believe it will be as «expensive» as you think. psutil is an excellent cross-platform python module cable of enumerating all the running programs on a system.

import psutil "someProgram" in (p.name() for p in psutil.process_iter()) 

Although @zeller said it already here is an example how to use tasklist . As I was just looking for vanilla python alternatives.

import subprocess def process_exists(process_name): call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name # use buildin check_output right away output = subprocess.check_output(call).decode() # check in last line for process name last_line = output.strip().split('\r\n')[-1] # because Fail message could be translated return last_line.lower().startswith(process_name.lower()) 
>>> process_exists('eclipse.exe') True >>> process_exists('AJKGVSJGSCSeclipse.exe') False 

To avoid calling this multiple times and have an overview of all the processes this way you could do something like:

# get info dict about all running processes import subprocess output = subprocess.check_output(('TASKLIST', '/FO', 'CSV')).decode() # get rid of extra " and split into lines output = output.replace('"', '').split('\r\n') keys = output[0].split(',') proc_list = [i.split(',') for i in output[1:] if i] # make dict with proc names as keys and dicts with the extra nfo as values proc_dict = dict((i[0], dict(zip(keys[1:], i[1:]))) for i in proc_list) for name, values in sorted(proc_dict.items(), key=lambda x: x[0].lower()): print('%s: %s' % (name, values)) 

win32ui.FindWindow(classname, None) returns a window handle if any window with the given class name is found. It raises window32ui.error otherwise.

import win32ui def WindowExists(classname): try: win32ui.FindWindow(classname, None) except win32ui.error: return False else: return True if WindowExists("DropboxTrayIcon"): print "Dropbox is running, sir." else: print "Dropbox is running. not." 

I found that the window class name for the Dropbox tray icon was DropboxTrayIcon using Autohotkey Window Spy.

Читайте также:  Rules file in linux

How can I write Python code to support both Windows and Linux?, I would put everything that only works for one OS in one file, but with equal name. Then you could add something like this at the beginning

How can I find the current OS in Python? [duplicate]

If you want user readable data but still detailed, you can use platform.platform()

>>> import platform >>> platform.platform() 'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne' 

platform also has some other useful methods:

>>> platform.system() 'Windows' >>> platform.release() 'XP' >>> platform.version() '5.1.2600' 

Here’s a few different possible calls you can make to identify where you are, linux_distribution and dist seem to have gone from recent python versions, so they have a wrapper function here.

import platform import sys def linux_distribution(): try: return platform.linux_distribution() except: return "N/A" def dist(): try: return platform.dist() except: return "N/A" print("""Python version: %s dist: %s linux_distribution: %s system: %s machine: %s platform: %s uname: %s version: %s mac_ver: %s """ % ( sys.version.split('\n'), str(dist()), linux_distribution(), platform.system(), platform.machine(), platform.platform(), platform.uname(), platform.version(), platform.mac_ver(), )) 

The outputs of this script ran on a few different systems (Linux, Windows, Solaris, MacOS) and architectures (x86, x64, Itanium, power pc, sparc) is available here: https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version

Python version: ['2.6.4 (r264:75706, Aug 4 2010, 16:53:32) [C]'] dist: ('', '', '') linux_distribution: ('', '', '') system: SunOS machine: sun4u platform: SunOS-5.9-sun4u-sparc-32bit-ELF uname: ('SunOS', 'xxx', '5.9', 'Generic_122300-60', 'sun4u', 'sparc') version: Generic_122300-60 mac_ver: ('', ('', '', ''), '') 
Python version: ['2.7.16 (default, Dec 21 2020, 23:00:36) ', '[GCC Apple LLVM 12.0.0 (clang-1200.0.30.4) [+internal-os, ptrauth-isa=sign+stri'] dist: ('', '', '') linux_distribution: ('', '', '') system: Darwin machine: arm64 platform: Darwin-20.3.0-arm64-arm-64bit uname: ('Darwin', 'Nautilus.local', '20.3.0', 'Darwin Kernel Version 20.3.0: Thu Jan 21 00:06:51 PST 2021; root:xnu-7195.81.3~1/RELEASE_ARM64_T8101', 'arm64', 'arm') version: Darwin Kernel Version 20.3.0: Thu Jan 21 00:06:51 PST 2021; root:xnu-7195.81.3~1/RELEASE_ARM64_T8101 mac_ver: ('10.16', ('', '', ''), 'arm64') 

I usually use sys.platform to get the platform. sys.platform will distinguish between linux, other unixes, and OS X, while os.name is » posix » for all of them.

For much more detailed information, use the platform module. This has cross-platform functions that will give you information on the machine architecture, OS and OS version, version of Python, etc. Also it has os-specific functions to get things like the particular linux distribution.

This gives you the essential information you will usually need. To distinguish between, say, different editions of Windows, you will have to use a platform-specific method.

Читайте также:  Как проверить mysql linux

Determine if system is linux or windows Code Example, Queries related to “determine if system is linux or windows” · python detect os · check operating system python · detect os python · python check os

Portable way of checking if *some* user exists in either Linux or Windows?

as far as i know, there is no universal command for both distros, but you can check the env in your script

import platform my_os = platform.system() 

based on this you can create different functions for both os.

Python check if platform is windows or linux Code Example, “python check if platform is windows or linux” Code Answer · python check is os is windows · Browse Python Answers by Framework.

Источник

How do I check the operating system in Python?

I want to check the operating system (on the computer where the script runs). I know I can use os.system(‘uname -o’) in Linux, but it gives me a message in the console, and I want to write to a variable. It will be okay if the script can tell if it is Mac, Windows or Linux. How can I check it?

5 Answers 5

from sys import platform if platform == "linux" or platform == "linux2": # linux elif platform == "darwin": # OS X elif platform == "win32": # Windows. 

sys.platform has finer granularity than sys.name .

For the valid values, consult the documentation.

Note that since Python 3.3, «linux2» is no longer a possible value of platform (see the linked docs for corroboration) and so if you only need to support Python 3.3 and later you can safely delete the ` or platform == «linux2″` clause from the first condition.

If you want to know on which platform you are on out of «Linux», «Windows», or «Darwin» (Mac), without more precision, you should use:

>>> import platform >>> platform.system() 'Linux' # or 'Windows'/'Darwin' 

The platform.system function uses uname internally.

I like this solution but I want to point out that from the docs it states that it will return Linux , Windows , Java or an empty string.devdocs.io/python~3.7/library/platform#platform.system

@BrandonBenefield, the enumeration is an example of possible values. On Apple devices, it returns “Darwin”.

You can get a pretty coarse idea of the OS you’re using by checking sys.platform .

Once you have that information you can use it to determine if calling something like os.uname() is appropriate to gather more specific information. You could also use something like Python System Information on unix-like OSes, or pywin32 for Windows.

There’s also psutil if you want to do more in-depth inspection without wanting to care about the OS.

os.uname() returns an error on windows: >>> os.uname() Traceback (most recent call last): File ««, line 1, in AttributeError: module ‘os’ has no attribute ‘uname’. Did you mean: ‘name’?

Источник

Оцените статью
Adblock
detector