以下while循环在运行IOError除外时停止
我得到了输出:
IP:192.168.1.1,PORT:80,已建立连接
IP: 192.168.1.1 ,PORT: 22 ,Connection established
IP: 192.168.1.1 ,PORT: 22 ,Connection established
IP: 192.168.1.1 ,PORT: 22 ,Connection established
IP: 192.168.1.97 ,PORT: 22 ,Cannot Connect (stops here)
任何帮助都会很棒。我不明白为什么它会运行IOError除外,然后停止
谢谢
while True:
f = input('Type the File Name/Path:')
if f == '': break
try:
with open(f, 'r', encoding='utf-8') as f:
for check in f:
check = check.split("\t")
HOSTNAME = check[0]
IP = check[1]
PORT = int(check[2])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(TIMEOUT)
s.connect((IP, PORT))
f = open("output.txt", "a")
print('IP:', IP, ',' 'PORT:', PORT, ',' "Connection established", file=f)
time.sleep(1)
f.close()
s.close()
except IOError:
f = open("output.txt", "a")
print('IP:', IP,',' 'PORT:', PORT,',' "Cannot Connect", file=f)
f.close()
except FileNotFoundError:
print("\n")
print('The file {} does not exist'.format(f))
input('Press ENTER to continue...')
print("\n")
break
答案 0 :(得分:0)
如果IO错误是由套接字调用引起的,我认为您的try/except
语句必须进行一些更改。您可以尝试:
while True:
file = input('Type the File Name/Path:')
if file == '':
break
try:
with open(file, 'r', encoding='utf-8') as f:
for check in f:
check = check.split("\t")
HOSTNAME = check[0]
IP = check[1]
PORT = int(check[2])
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(TIMEOUT)
s.connect((IP, PORT))
s.close()
except IOError:
log = open("output.txt", "a")
print('IP:', IP,',' 'PORT:', PORT,',' "Cannot Connect", file=log)
log.close()
continue # will go back to the beginning of the while loop
log = open("output.txt", "a")
print('IP:', IP, ',' 'PORT:', PORT, ',' "Connection established", file=log)
log.close()
time.sleep(1)
except FileNotFoundError:
print('\nThe file {} does not exist'.format(file))
input('Press any key to continue...\n')
break