man: add example os-release mangling in python

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.
This commit is contained in:
Zbigniew Jędrzejewski-Szmek 2021-05-20 20:00:18 +02:00
parent e839ebe551
commit 3ca606d103
2 changed files with 36 additions and 0 deletions

28
man/check-os-release.py Normal file
View file

@ -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!')

View 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>