【问题标题】:How to make sure enter keys are not being input to password如何确保输入键没有被输入密码
【发布时间】:2012-11-11 00:53:23
【问题描述】:

我遇到以下问题,当 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

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    我认为您应该在读取密码之前尝试刷新用户输入。

    为此,查看this other post 可能会有所帮助。

    【讨论】:

      【解决方案2】:

      Kosklain 的回答应该让您走上正轨。但是,通过您提出问题的方式,您似乎不知道导致此行为的过程,因此这里有一些关于正在发生的事情的更多见解:

      出现这种情况是因为系统会缓冲(保存在内存中)您的整个输入流,即使您实际上并未请求输入。当(假设)您执行raw_input() 时,它所做的只是读取 sys.stdin 直到找到换行符。显然,如果在您最近引入的输入行之前有一个换行符,它就会停在那里。

      因此,您的问题的解决方案如下:

      while there_is_a_new_line():
          line= raw_input()
      

      there_is_a_new_line() 函数,然而,结果是有点复杂。现有的解决方案涉及更改终端的属性,并且不是跨平台的。有关详细信息,请参阅 kosklain 的链接。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-09
        • 1970-01-01
        • 2019-01-29
        • 1970-01-01
        • 1970-01-01
        • 2019-11-20
        相关资源
        最近更新 更多