Exception handling is used in Python to determine which operating system platform method is running

  • 2020-04-02 14:31:50
  • OfStack

Code example:


try:
    import termios, TERMIOS               1
except ImportError:
    try:
        import msvcrt                  2
    except ImportError:
        try:
            from EasyDialogs import AskPassword   3
        except ImportError:
            getpass = "default_getpass"        4
        else:
            getpass = "AskPassword"          5
    else:
        getpass = "win_getpass"
else:
    getpass = "unix_getpass"

1: termios is a unix-only module that provides the underlying control over the input terminal. If the module is invalid (because it is not on your system, or your system does not support it), the import fails, and Python throws the ImportError exception we caught.

2: OK, we don't have termios, so let's try MSVCRT, a windows-only module that provides an API for many useful functions in Microsoft Visual C++ running services. If the import fails, Python throws the ImportError exception we caught.

3: if the first two don't work, let's try importing a function from EasyDialogs, which is a module unique to Mac OS and provides various types of pop-up dialog boxes. Again, if the import fails, Python throws an ImportError exception that we caught.

4: none of these platform-specific modules are valid (probably because Python has been ported to many different platforms), so we need to go back to using a default password input function (defined elsewhere in the getpass module). Notice what we did here: we assigned the function default_getpass to the variable getpass. If you read the official getpass document, it will tell you that the getpass module defines a getpass function. Here's what it does: it ADAPTS to your platform by binding getpass to the correct function. And then when you call the getpass function, you're actually calling a platform-specific function that this code has set up for you. You don't need to know or care what platform your code is running on; As long as getpass is called, it always handles it correctly.

5: a try... An except block can have an else clause, just like an if statement. If no exception is thrown in the try block, then the else clause is executed. In this case, that means that if the AskPassword import from EasyDialogs import works, we should bind getpass to the AskPassword function. Every other try... The except block has a similar else clause, and when we find an import available, we bind getpass to the appropriate function.


Related articles: