5

I would like to add a check in a python 2.7.x script in the form of

if __check_freebsd__():
    # run actions which would only work on FreeBSD (e.g. create a jail)
elif __check_debian__():
    # run an alternative that runs on Debian-based systems
else:
    raise Error("unsupported OS")

How would the __check_freebsd__ function look like?

I have the following code for __check_debian__ already:

try:
    lsb_release_id_short = sp.check_output([lsb_release, "-d", "-s"]).strip().decode("utf-8")
    ret_value = "Debian" in lsb_release_id_short
    return ret_value
except Exception:
    return False

So you don't have to bother with it (suggestions for improvements are welcome, of course).

Kalle Richter
  • 8,008
  • 26
  • 77
  • 177

3 Answers3

3

As stated in documentation,

platform.system()

returns the platform OS name, so you can use this. In this thread you can see also different approaches to check the underlying OS.

Community
  • 1
  • 1
Adalee
  • 528
  • 12
  • 26
  • `if platform.system() == 'FreeBSD'` should work, as far as I am concerned. Karl asked about freeBSD check, so I think I don't need to check Linux distros. If I am wrong, please correct me. – Adalee May 03 '15 at 16:01
  • Works on FreeBSD 9.3 and FreeBSD 10.0. – Kalle Richter May 03 '15 at 23:16
1

Look at os.uname.

I'm not 100% certain, but it would probably be something like os.uname()[0] == "FreeBSD".

Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
orlp
  • 112,504
  • 36
  • 218
  • 315
1

Try this:

>>> from sys import platform
>>> platform()
# on my system I get
'linux' # check string for freebsd

Also:

# below are my results
>>> import platform
>>> platform.system()
'Linux' # would be 'FreeBSD' if I was using that
>>> platform.platform()
'Linux-3.19.0-15-generic-x86_64-with-Ubuntu-15.04-vivid'
Totem
  • 7,189
  • 5
  • 39
  • 66
  • `platform.linux_platform()` returns `('', '', '')` in FreeBSD 9.3 (running on `qemu` 2.2). – Kalle Richter May 03 '15 at 23:12
  • @KarlRichter it's only for linux, so it wouldn't work for FreeBSD I suppose. platform.system() is cross platform though as is sys.platform – Totem May 03 '15 at 23:19
  • I see. Then it's not an answer to my question, is it? Maybe this is due to `qemu`? – Kalle Richter May 04 '15 at 01:02
  • @KarlRichter No, it is. sys.platform, platform.system and platform.platform all give you the info you want. The first two in a more straight-forward fashion. I had included the platform.linux_platform also, I can't remember why. But I edited it out earlier. – Totem May 04 '15 at 02:20