opsi packages that support Python 2 and 3

The work on opsi 4.2 is ongoing and the switch of Python versions means that we also have to look for the helper scripts that come with our opsi packages. There is a simple pattern I follow to make sure that we can use a package with opsi 4.1 and 4.2 I will show here.

First I make sure that the script runs fine with Python 2 and 3. As the standard library of Python changed you can use a tool like 2to3 that will aid you in changing the code the be working with Python 3. I won't go into detail about this here because there are a lot of resources on the internet on how to deal with these changes - python3porting is one I like a lot. Scripts that make use of the OPSI package (provided through python-opsi) are usually without any need to change imports or usage.

When we have a script that can be run with Python 2 and 3 we are changing the used interpreter. These helper scripts are executable and specify the used program through the shebang line - this is the first line that usually starts with #!. I will adjust this so our script is running with Python 3 by using the following: #!/usr/bin/python3

This makes the script running with Python 3 by default. For Python 2 we will modify the file to run with the older version instead.

To achieve this I add the following to the OPSI/postinst of the package:

# Patching scripts to work with opsi 4.1 and opsi 4.2
set +e
python3 -c "import OPSI"
ret=$?
set -e
if [ $ret -eq 0 ]; then
        # Python 3 - opsi 4.2 or later
        echo "Running on opsi 4.2 or later. Nothing to do."
else
        echo "Running on opsi 4.1. Patching scripts..."
        # Python 2 - opsi 4.1
        sed --in-place "s_/usr/bin/python3_/usr/bin/python_" "$CLIENT_DATA_DIR/my_script.py"
fi

Once support for Python 2 is completely dropped we will be able to simply remove this part from the postinst and call it a day.