|
5 | 5 | ----------
|
6 | 6 | 问题
|
7 | 7 | ----------
|
8 |
| -You’ve written a script that requires a password, but since the script is meant for inter‐ |
9 |
| -active use, you’d like to prompt the user for a password rather than hardcode it into the |
10 |
| -script. |
| 8 | +你写了个脚本,运行时需要一个密码。此脚本是交互式的,因此不能将密码在脚本中硬编码, |
| 9 | +而是需要弹出一个密码输入提示,让用户自己输入。 |
11 | 10 |
|
12 | 11 | |
|
13 | 12 |
|
14 | 13 | ----------
|
15 | 14 | 解决方案
|
16 | 15 | ----------
|
17 |
| -Python’s getpass module is precisely what you need in this situation. It will allow you |
18 |
| -to very easily prompt for a password without having the keyed-in password displayed |
19 |
| -on the user’s terminal. Here’s how it’s done: |
| 16 | +这时候Python的 ``getpass`` 模块正是你所需要的。你可以让你很轻松的弹出密码输入提示, |
| 17 | +并且不会在用户终端回显密码。下面是具体代码: |
20 | 18 |
|
21 |
| -import getpass |
| 19 | +.. code-block:: python |
22 | 20 |
|
23 |
| -user = getpass.getuser() |
24 |
| -passwd = getpass.getpass() |
| 21 | + import getpass |
25 | 22 |
|
26 |
| -if svc_login(user, passwd): # You must write svc_login() |
27 |
| - print('Yay!') |
28 |
| -else: |
29 |
| - print('Boo!') |
| 23 | + user = getpass.getuser() |
| 24 | + passwd = getpass.getpass() |
30 | 25 |
|
31 |
| -In this code, the svc_login() function is code that you must write to further process |
32 |
| -the password entry. Obviously, the exact handling is application-specific. |
| 26 | + if svc_login(user, passwd): # You must write svc_login() |
| 27 | + print('Yay!') |
| 28 | + else: |
| 29 | + print('Boo!') |
| 30 | +
|
| 31 | +在此代码中,``svc_login()`` 是你要实现的处理密码的函数,具体的处理过程你自己决定。 |
33 | 32 |
|
34 | 33 | |
|
35 | 34 |
|
36 | 35 | ----------
|
37 | 36 | 讨论
|
38 | 37 | ----------
|
39 |
| -Note in the preceding code that getpass.getuser() doesn’t prompt the user for their |
40 |
| -username. Instead, it uses the current user’s login name, according to the user’s shell |
41 |
| -environment, or as a last resort, according to the local system’s password database (on |
42 |
| -platforms that support the pwd module). |
| 38 | +注意在前面代码中 ``getpass.getuser()`` 不会弹出用户名的输入提示。 |
| 39 | +它会根据该用户的shell环境或者会依据本地系统的密码库(支持 `pwd` 模块的平台)来使用当前用户的登录名, |
| 40 | + |
| 41 | +如果你想显示的弹出用户名输入提示,使用内置的 ``input`` 函数: |
43 | 42 |
|
44 |
| -If you want to explicitly prompt the user for their username, which can be more reliable, |
45 |
| -use the built-in input function: |
| 43 | +.. code-block:: python |
46 | 44 |
|
47 |
| -user = input('Enter your username: ') |
| 45 | + user = input('Enter your username: ') |
48 | 46 |
|
49 |
| -It’s also important to remember that some systems may not support the hiding of the |
50 |
| -typed password input to the getpass() method. In this case, Python does all it can to |
51 |
| -forewarn you of problems (i.e., it alerts you that passwords will be shown in cleartext) |
52 |
| -before moving on. |
| 47 | +还有一点很重要,有些系统可能不支持 ``getpass()`` 方法隐藏输入密码。 |
| 48 | +这种情况下,Python会提前警告你这些问题(例如它会警告你说密码会以明文形式显示) |
0 commit comments