pythonpython-3.xsyntax-errorpython-3.4

Fix Python3 syntax error in CheckMK plugin


I'm using CheckMK 2.2.0 and its plugin for Nginx to monitor some hosts. The agent is running on a host using Python 3.4.2 that can not be updated. When running the Nginx plugin on this host, I'm getting a syntax error:

# python3 nginx_status.py
  File "nginx_status.py", line 126
    config: dict = {}
          ^
SyntaxError: invalid syntax

The code looks like:

def main():  # pylint: disable=too-many-branches
    config_dir = os.getenv("MK_CONFDIR", "/etc/check_mk")
    config_file = config_dir + "/nginx_status.cfg"

    config: dict = {}
    if os.path.exists(config_file):
        with open(config_file) as open_config_file:
            config_src = open_config_file.read()
            exec(config_src, globals(), config)

Running this script on another host using Python 3.11.2 it works. But as I've said, I'm not able to update the elder Python version. I'm a PHP programmer, but have no knowledge of Python.

What is this type of code config: dict = {} and how to fix it to run on Python 3.4?


Solution

  • Python 3.4 is too old to support type annotations. You really should get it upgraded to a secure and supported version. 3.4 reached end of life on 2019-03-18.

    In the interim, the workaround is to remove any type annotations from the source code. Anything which looks like variable: type = value or variable: type should lose the : type part. Similarly, function definitions with a -> returntype annotation should lose that.

    For example,

    def foo(bar: int, baz: str = "") -> bool:
       temp: str = f"{bar}!={baz}"
       return temp == "1!=2"
    

    should be refactored to

    def foo(bar, baz=""):
       temp = f"{bar}!={baz}"
       return temp == "1!=2"
    

    for backwards compatibility.