python尝试,但套接字不工作
我的代码是:python尝试,但套接字不工作,python,sockets,try-catch,except,Python,Sockets,Try Catch,Except,我的代码是: usso = socket.gethostbyname("site.com") try: usso except socket.gaierror: uss = 0 else: uss = 1 if uss == 1: print ("Site Is True") elif uss == 0: print ("Site Is Wrong") 但除不起作用外,结果是: Traceback (most recent call last): F
usso = socket.gethostbyname("site.com")
try:
usso
except socket.gaierror:
uss = 0
else:
uss = 1
if uss == 1:
print ("Site Is True")
elif uss == 0:
print ("Site Is Wrong")
但除不起作用外,结果是:
Traceback (most recent call last):
File "test.py", line 22, in <module>
usso = socket.gethostbyname("site.com")
socket.gaierror: [Errno -2] Name or service not known
回溯(最近一次呼叫最后一次):
文件“test.py”,第22行,在
usso=socket.gethostbyname(“site.com”)
socket.gaierror:[Errno-2]名称或服务未知
问题是什么?您必须将可能导致异常的语句放入try-catch块。在原始代码中,异常发生在try-catch块之前,即第一行 试试这个
try:
usso = socket.gethostbyname("site.com")
except socket.gaierror:
uss = 0
您的代码未包含在“try”块中。
应该是:
try:
usso = socket.gethostbyname("site.com")
except socket.gaierror:
print 'yolos'