首页 > 解决方案 > 如何修复 getpassWarning 并正确使用 getpass?

问题描述

所以...我只想要这个。我正在尝试用 Python 制作游戏“信任游戏”。这是一个你可以背叛或不背叛伴侣的游戏。这是我正在制作的代码:

p1_point = 0
p2_point = 0
x = int(input("How many levels? "))
while x != 0:
    p1 = input("Player 1, pick yes to agree or no to betray. ") #I want to change this.
    p2 = input("Player 2, pick yes to agree or no to betray. ") #I want to change this.
    if p1 == "yes" and p2 == "yes":
        p1_point += 5
        p1_point += 5
    elif p1 == "yes" and p2 == "no":
        p1_point -= 2
        p2_point += 10
    elif p1 == "no" and p2 == "yes":
        p1_point += 10
        p2_point -= 2
    elif p1 == "no" and p2 == "no":
        p1_point -= 5
        p2_point -= 5
    print("Player 1 said {} and Player 2 said {}.".format(p1, p2))
    print("Player 1's score is now {} and Player 2's score is now {}.".format(p1_point, p2_point))
    x -= 1
if p1_point > p2_point:
    print("Player 1 wins!")
elif p1_point < p2_point:
    print("Player 2 wins!")
elif p1_point == p2_point:
    print("It's a tie!")

但我想像这样输入:

****

所以他们不会作弊。

看到有人说要用getpass模块,我是这样用的。

p1 = getpass.getpass(prompt = "Player 1, pick yes to agree or no to betray. ", stream = None)
p2 = getpass.getpass(prompt = "Player 2, pick yes to agree or no to betray. ", stream = None)

但是有一个getpassWarning。

(from warnings module):
File "C:\Program Files (x86)\Microsoft Visual 
Studio\Shared\Python36_64\lib\getpass.py", line 100
return fallback_getpass(prompt, stream)
GetPassWarning: Can not control echo on the terminal.
Warning: Password input may be echoed.
Player 1, pick yes to agree or no to betray.

我怎样才能解决这个问题?以及如何使用 getpass?

标签: pythonpython-3.xinput

解决方案


您可以使用getpass

import getpass

pswd = getpass.getpass('Password:')

这应该可以完成这项工作。如果你得到一个 getPassWarning,你可以试试这个

import sys
import msvcrt

passwor = ''
while True:
    x = msvcrt.getch()
    if x == '\r':
        break
    sys.stdout.write('*')
    passwor +=x

print '\n'+passwor

推荐阅读