code example:
Copy CodeThe code is as follows:
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"
The 1:termios is a UNIX-only module that provides the underlying control of the input terminal. If this module is not valid (because it is not on your system, or your system does not support it), then the import fails, and Python throws the Importerror exception we caught.
2:ok, we don't have termios, so let's try Msvcrt, which is a module unique to Windows that can provide 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 do not work, we try to import a function from Easydialogs, which is a module unique to Mac OS and provides various types of pop-up dialogs. Once again, if the import fails, Python throws a Importerror exception that we caught.
4: None of these platform-specific modules are valid (possibly, because Python has been ported to many different platforms), so we need to go back and use a default password input function (which is defined elsewhere in the Getpass module). Notice what we do here: we assign 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. It does this by binding getpass to the correct function to suit your platform. Then when you call the Getpass function, you actually call the platform-specific function, which is already set for you. You don't need to know or care what kind of platform your code is running on, and as long as you call Getpass, it's always handled correctly.
5: A try...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 from Easydialogs import Askpassword is working, we should bind the Getpass to the Askpassword function. Each other try...except block has a similar else clause and binds getpass to the appropriate function when we find that an import is available.