Python test if linux

How to check if a process is still running using Python on Linux? [duplicate]

Mark’s answer is the way to go, after all, that’s why the /proc file system is there. For something a little more copy/pasteable:

 >>> import os.path >>> os.path.exists("/proc/0") False >>> os.path.exists("/proc/12") True 

on linux, you can look in the directory /proc/$PID to get information about that process. In fact, if the directory exists, the process is running.

It should work on any POSIX system (although looking at the /proc filesystem, as others have suggested, is easier if you know it’s going to be there).

However: os.kill may also fail if you don’t have permission to signal the process. You would need to do something like:

import sys import os import errno try: os.kill(int(sys.argv[1]), 0) except OSError, err: if err.errno == errno.ESRCH: print "Not running" elif err.errno == errno.EPERM: print "No permission to signal this process!" else: print "Unknown error" else: print "Running" 

I use this to get the processes, and the count of the process of the specified name

import os processname = 'somprocessname' tmp = os.popen("ps -Af").read() proccount = tmp.count(processname) if proccount > 0: print(proccount, ' processes running of ', processname, 'type') 

Here’s the solution that solved it for me:

import os import subprocess import re def findThisProcess( process_name ): ps = subprocess.Popen("ps -eaf | grep "+process_name, shell=True, stdout=subprocess.PIPE) output = ps.stdout.read() ps.stdout.close() ps.wait() return output # This is the function you can use def isThisRunning( process_name ): output = findThisProcess( process_name ) if re.search('path/of/process'+process_name, output) is None: return False else: return True # Example of how to use if isThisRunning('some_process') == False: print("Not running") else: print("Running!") 

I’m a Python + Linux newbie, so this might not be optimal. It solved my problem, and hopefully will help other people as well.

This solution will give wrong results if one tries to search a process only by name, without full path ‘path/of/process’, because «ps -eaf | grep» will also include the grep process itself, thus always providing non-empty output.

But is this reliable? Does it work with every process and every distribution?

Yes, it should work on any Linux distribution. Be aware that /proc is not easily available on Unix based systems, though (FreeBSD, OSX).

Источник

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?

Читайте также:  Linux узнать размер видеокарты

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’?

Источник

How to identify which OS Python is running on

The output of platform.system() is as follows:

@matth Slightly more consistent output. i.e. platform.system() returns «Windows» instead of «win32» . sys.platform also contains «linux2» on old versions of Python while it contains just «linux» on newer ones. platform.system() has always returned just «Linux» .

@baptistechéné, I know this has over an year since you asked, but as a comment won’t hurt, I’ll post it anyways 🙂 So, the reason behind it is because it shows the kernel name. The same way Linux (the kernel) distros have many names (Ubuntu, Arch, Fedora among others), but it’ll present itself as the kernel name, Linux. Darwin (a BSD-based Kernel), has its surrounding system, the macOS. I’m pretty sure apple did release Darwin as an open source code, but there’s no other distro running over Darwin that I know of.

Читайте также:  Listen on tcp port linux

@TooroSan os.uname() only exists for Unix systems. The Python 3 docs: docs.python.org/3/library/os.html Availability: recent flavors of Unix.

Here are the system results for Windows Vista!

>>> import os >>> os.name 'nt' >>> import platform >>> platform.system() 'Windows' >>> platform.release() 'Vista' 
>>> import os >>> os.name 'nt' >>> import platform >>> platform.system() 'Windows' >>> platform.release() '10' 

So, yeah, I just ran platform.release() on my Windows 10, and it definitely just gave me ‘8’ . Maybe I installed python before upgrading, but really??

I’d have thought it’s more likely you upgraded from Windows 8 (vs. it being a clean install) and whatever Python looks up in the registry or whatever was left behind?

The release lookup for python on Windows appears to use the Win32 api function GetVersionEx at its core. The notes at the top of this Microsoft article about that function could be relevant: msdn.microsoft.com/en-us/library/windows/desktop/…

For the record, here are the results on Mac:

>>> import os >>> os.name 'posix' >>> import platform >>> platform.system() 'Darwin' >>> platform.release() '8.11.1' 

19.2.0 is the release version of Darwin that comes with Catalina 10.15.2: en.wikipedia.org/wiki/MacOS_Catalina#Release_history

Sample code to differentiate operating systems using Python:

import sys if sys.platform.startswith("linux"): # could be "linux", "linux2", "linux3", . # linux elif sys.platform == "darwin": # MAC OS X elif os.name == "nt": # Windows, Cygwin, etc. (either 32-bit or 64-bit) 

Little problem: win64 does not exis: github.com/python/cpython/blob/master/Lib/platform.py. All Windows versions are win32 .

Short Story

Use platform.system() . It returns Windows , Linux or Darwin (for OS X).

There are three ways to get the OS in Python, each with its own pro and cons:

>>> import sys >>> sys.platform 'win32' # could be 'linux', 'linux2, 'darwin', 'freebsd8' etc 

How this works (source): Internally it calls OS APIs to get the name of the OS as defined by the OS. See here for various OS-specific values.

Con: OS version dependent, so best not to use directly.

>>> import os >>> os.name 'nt' # for Linux and Mac it prints 'posix' 

How this works (source): Internally it checks if Python has OS-specific modules called posix or nt.

Pro: Simple to check if it is a POSIX OS

Con: no differentiation between Linux or OS X.

>>> import platform >>> platform.system() 'Windows' # For Linux it prints 'Linux'. For Mac, it prints `'Darwin' 

How this works (source): Internally it will eventually call internal OS APIs, get the OS version-specific name, like ‘win32’ or ‘win16’ or ‘linux1’ and then normalize to more generic names like ‘Windows’ or ‘Linux’ or ‘Darwin’ by applying several heuristics.

Pro: The best portable way for Windows, OS X, and Linux.

Читайте также:  Linux ls tree view

Con: Python folks must keep normalization heuristic up to date.

  • If you want to check if OS is Windows or Linux, or OS X, then the most reliable way is platform.system() .
  • If you want to make OS-specific calls, but via built-in Python modules posix or nt , then use os.name .
  • If you want to get the raw OS name as supplied by the OS itself, then use sys.platform .

So much for «There should be one (and preferably only one) way to do things». However I believe this is the right answer. You would need to compare with titled OS names but it’s not such an issue and will be more portable.

Note that in Python 3.10 , platform.system defaults to sys.platform if the os.uname throws an exception: github.com/python/cpython/blob/…

I started a bit more systematic listing of what values you can expect using the various modules:

Linux (64 bit) + WSL

 x86_64 aarch64 ------ ------- os.name posix posix sys.platform linux linux platform.system() Linux Linux sysconfig.get_platform() linux-x86_64 linux-aarch64 platform.machine() x86_64 aarch64 platform.architecture() ('64bit', '') ('64bit', 'ELF') 
  • I tried with Arch Linux and Linux Mint, but I got the same results
  • on Python 2, sys.platform is suffixed by the kernel version, e.g., linux2 , and everything else stays identical
  • the same output on Windows Subsystem for Linux (I tried with Ubuntu 18.04 (Bionic Beaver) LTS), except platform.architecture() = (’64bit’, ‘ELF’)

Windows (64 bit)

(with 32-bit column running in the 32-bit subsystem)

Official Python installer 64 bit 32 bit ------------------------- ----- ----- os.name nt nt sys.platform win32 win32 platform.system() Windows Windows sysconfig.get_platform() win-amd64 win32 platform.machine() AMD64 AMD64 platform.architecture() ('64bit', 'WindowsPE') ('64bit', 'WindowsPE') msys2 64 bit 32 bit ----- ----- ----- os.name posix posix sys.platform msys msys platform.system() MSYS_NT-10.0 MSYS_NT-10.0-WOW sysconfig.get_platform() msys-2.11.2-x86_64 msys-2.11.2-i686 platform.machine() x86_64 i686 platform.architecture() ('64bit', 'WindowsPE') ('32bit', 'WindowsPE') msys2 mingw-w64-x86_64-python3 mingw-w64-i686-python3 ----- ------------------------ ---------------------- os.name nt nt sys.platform win32 win32 platform.system() Windows Windows sysconfig.get_platform() mingw mingw platform.machine() AMD64 AMD64 platform.architecture() ('64bit', 'WindowsPE') ('32bit', 'WindowsPE') Cygwin 64 bit 32 bit ------ ----- ----- os.name posix posix sys.platform cygwin cygwin platform.system() CYGWIN_NT-10.0 CYGWIN_NT-10.0-WOW sysconfig.get_platform() cygwin-3.0.1-x86_64 cygwin-3.0.1-i686 platform.machine() x86_64 i686 platform.architecture() ('64bit', 'WindowsPE') ('32bit', 'WindowsPE') 
  • there is also distutils.util.get_platform() which is identical to `sysconfig.get_platform
  • Anaconda on Windows is the same as the official Python Windows installer
  • I don’t have a Mac nor a true 32-bit system and was not motivated to do it online

To compare with your system, simply run this script:

from __future__ import print_function import os import sys import platform import sysconfig print("os.name ", os.name) print("sys.platform ", sys.platform) print("platform.system() ", platform.system()) print("sysconfig.get_platform() ", sysconfig.get_platform()) print("platform.machine() ", platform.machine()) print("platform.architecture() ", platform.architecture()) 

Источник

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