我希望让我的脚本在继续执行脚本的其余部分之前验证电子邮件密码是否正确。我确定它只是一个简单的循环,但我无法想到一个简单的方法。现在我的脚本是:
import arcpy, os, sys, time, subprocess, collections, datetime, smtplib
from datetime import datetime
print("This script will check your email password to verify it is correct.")
usr = "your_email@gmail.com"
print("Please enter the password for " + usr + ":")
psw = raw_input()
def passwordcheck(usr,psw):
server=smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(usr,psw)
server.quit()
print("Thank you. Password was correct.")
try:
passwordcheck(usr,psw)
except:
print("Password was incorrect.")
我想要一个简单的循环,允许用户3尝试输入正确的密码,然后如果没有输入正确的密码,请终止该脚本。
答案 0 :(得分:1)
这会更有意义。
def passwordcheck(usr,psw):
server=smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
try:
server.login(usr,psw)
ret = True
except:
ret = False
server.quit()
return ret
for i in range(3):
psw = raw_input("Please enter the password for " + usr + ": ")
if passwordcheck(usr,psw) is False:
print("Password was incorrect.")
else:
print("Thank you. Password was correct.")
break
因为处理错误源附近的错误并相应地采取行动应该(是?)被认为是最佳实践。
另外,考虑到你将Password was incorrect
保留在函数调用之外,你应该保持正输出关闭(始终保持相似的输出彼此接近)。
因此处理passwordcheck
中的错误并处理函数的返回码
这可能不是SO的典型问题,因为您的初始代码没有任何问题,因为更多的是代码审查可以考虑它。
答案 1 :(得分:0)
这样的事情应该这样做:
def passwordcheck(usr)
print("This script will check your email password to verify it is correct.")
usr = "your_email@gmail.com"
for i in range(3):
print("Please enter the password for " + usr + ":")
psw = raw_input()
try:
server=smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(usr,psw)
server.quit()
print "Thank you. Password was correct."
break
except:
if i < 3:
print "Password was incorrect. Try again:"
continue
print "Password was incorrect. 3 times"
break