Skip to content

Commit aaa9b9c

Browse files
committed
13.4小节完成
1 parent a374e65 commit aaa9b9c

File tree

1 file changed

+22
-26
lines changed

1 file changed

+22
-26
lines changed

source/c13/p04_prompt_for_password_at_runtime.rst

Lines changed: 22 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -5,48 +5,44 @@
55
----------
66
问题
77
----------
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+
而是需要弹出一个密码输入提示,让用户自己输入。
1110

1211
|
1312
1413
----------
1514
解决方案
1615
----------
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+
并且不会在用户终端回显密码。下面是具体代码:
2018

21-
import getpass
19+
.. code-block:: python
2220
23-
user = getpass.getuser()
24-
passwd = getpass.getpass()
21+
import getpass
2522
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()
3025
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()`` 是你要实现的处理密码的函数,具体的处理过程你自己决定。
3332

3433
|
3534
3635
----------
3736
讨论
3837
----------
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`` 函数:
4342

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
4644
47-
user = input('Enter your username: ')
45+
user = input('Enter your username: ')
4846
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

Comments
 (0)