I'm trying catch the exception but the script continues and outputs none
when something goes wrong with the proxy connection such as Socket Error: Socket error: [Errno 104] Connection reset by peer
for the expiration date of google
import socket
import socks
import whois
import requests
try:
r = requests.get('http://gimmeproxy.com/api/getProxy?protocol=socks5&maxCheckPeriod=3600').json()
socks.set_default_proxy(socks.SOCKS5, r['ip'], int(r['port']))
print(r['ip'], int(r['port']))
socket.socket = socks.socksocket
w = whois.whois('google.com')
print(w.expiration_date)
except Exception as msg:
print(msg) #never actually prints this
To catch socket exceptions you need to catch OSError
exceptions.
Following code will work as expected:
import socket
import socks
import whois
import requests
exitcode = 0
try:
r = requests.get('http://gimmeproxy.com/api/getProxy?protocol=socks5&maxCheckPeriod=3600').json()
socks.set_default_proxy(socks.SOCKS5, r['ip'], int(r['port']))
print(r['ip'], int(r['port']))
socket.socket = socks.socksocket
w = whois.whois('google.com')
print(w.expiration_date)
except OSError as msg:
print(msg)
Also you may use another version of this script. It will return an appropriate exit code as result of script execution:
import socket
import socks
import whois
import requests
exitcode = 0
try:
r = requests.get('http://gimmeproxy.com/api/getProxy?protocol=socks5&maxCheckPeriod=3600').json()
socks.set_default_proxy(socks.SOCKS5, r['ip'], int(r['port']))
print(r['ip'], int(r['port']))
socket.socket = socks.socksocket
w = whois.whois('google.com')
print(w.expiration_date)
except OSError as msg:
print(msg)
exitcode = 1
exit(exitcode)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.