]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
man: add example os-release mangling in python
authorZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
Thu, 20 May 2021 18:00:18 +0000 (20:00 +0200)
committerZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
Fri, 21 May 2021 14:33:04 +0000 (16:33 +0200)
This is also not entirely obvious. I think the code I came
up with is pretty elegant ;] The final part of of the code that makes
use of the parsed data is kept very similar to the shell code on purpose,
even though it could be written a bit more idiomatically.

man/check-os-release.py [new file with mode: 0644]
man/os-release.xml

diff --git a/man/check-os-release.py b/man/check-os-release.py
new file mode 100644 (file)
index 0000000..f6d23c8
--- /dev/null
@@ -0,0 +1,28 @@
+#!/usr/bin/python
+
+import ast
+import re
+
+def read_os_release():
+    try:
+        f = open('/etc/os-release')
+    except FileNotFoundError:
+        f = open('/usr/lib/os-release')
+
+    for line_number, line in enumerate(f):
+        if m := re.match(r'([A-Z][A-Z_0-9]+)=(.*)', line):
+            name, val = m.groups()
+            if val and val[0] in '"\'':
+                val = ast.literal_eval(val)
+            yield name, val
+        else:
+            print(f'Warning: bad line {line_number}: {line}', file=sys.stderr)
+
+os_release = dict(read_os_release())
+
+pretty_name = os_release.get('PRETTY_NAME', 'Linux')
+print(f'Running on {pretty_name}')
+
+if (os_release.get('ID', 'linux') == 'debian' or
+    os_release.get('ID_LIKE', None) == 'debian'):
+    print('Looks like Debian!')
index 36e5bed62e3629d60a3b0fa1fb961b585e26ff65..a00b8a5264a3277fd5732819471d02dac54a8d37 100644 (file)
@@ -419,6 +419,14 @@ VARIANT_ID=workstation</programlisting>
 
       <programlisting><xi:include href="check-os-release.sh" parse="text" /></programlisting>
     </example>
+
+    <example>
+      <title>Reading <filename>os-release</filename> in
+      <citerefentry><refentrytitle>python</refentrytitle><manvolnum>1</manvolnum></citerefentry></title>
+
+      <programlisting><xi:include href="check-os-release.py" parse="text" /></programlisting>
+    </example>
+
   </refsect1>
 
   <refsect1>