How to determine if a Unix-like script works in the Python operating system?

I am trying to determine if the operating system is Unix-based from a Python script. I can imagine two ways to do this, but both of them have disadvantages:

  • Check if platform.system() in the tuple, for example ("Linux", "Darwin") . The problem is that I do not want to provide a list of each Unix-like system, each of which is made, in particular, there are many varieties of BSD.
  • Check if the os.fchmod function os.fchmod , as this function is available only on Unix. This is not like a clean or "pufonic" way to do it.
+4
source share
2 answers

Pythonic paths for this do not care about which platform you are on.

If there are several different possibilities for doing something depending on the platform, abstract them behind a function or class that should try the tool and switch to another one if this tool is not available on the current platform.

+6
source
 import sys if 'win' in sys.platform(): #windows else: #not windows 

or you can try importing a platform dependent library

 try: import windows_only as generic except ImportException: try: import unix_only as generic except ImportException: import stdlib.module as generic print generic.common_function() 

and then always reliable

 >>> import os >>> os.name nt 
+5
source

Source: https://habr.com/ru/post/1499209/


All Articles