0

我遇到以下问题,当 python 脚本运行时,用户在命令窗口上一直按“回车键”...以下是在命令窗口上运行的内容,但用户一直按回车键,最终输入密码和脚本失败,我该如何防止这种情况?

 Parsing the XML

 Building the build combo table

  **Password: //asks for password but user had multiple enter key presses above which is taken as passoword and fails**

Python代码:-

url='http://wiki.com/'+wikiName+'/w/index.php?title='+hId +'_'+rId+'&action=edit'
cookiehand = urllib2.HTTPCookieProcessor()
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(user=getpass.getuser(),passwd=getpass.getpass(),uri=authhost,realm=realm)
auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(auth_handler, cookiehand)
urllib2.install_opener(opener)
# make the request
req = urllib2.Request(url=url)
try:
    f = urllib2.urlopen(req)
    txt = f.read()
    f.close()
except urllib2.HTTPError, e:
    txt = ''
    print 'An error occured connecting to the wiki. No wiki page will be generated.'//eventually gets this error
4

1 回答 1

0

您需要做的是验证输入。像这样的东西:

user = ""
pass = ""

while not user and not pass:
    user = getpass.getuser()
    passwd = getpass.getpass()

请注意,如果允许使用空白密码,这将不起作用。如果您可以控制 getpass 库,则将验证移到这两个方法中可能更有意义,并且可能使用默认参数使它们成为可选参数,例如validate=False

于 2012-12-13T00:25:48.120 回答