Could you try the following ?
The snippet is expected to work in both PythonSlicer
and a regular python
interpreter.
import sys
import traceback
import urllib.request
def processEvents():
try:
import slicer
slicer.app.processEvents()
except (AttributeError, ImportError):
pass
def display(text, file=sys.stdout):
processEvents()
print(text, flush=True, file=file)
def error(text):
display(text, file=sys.stderr)
for url, expected_success in [
("https://data.kitware.com", True),
("https://www.httpvshttps.com/", True),
("https://slicer.org/", True),
("https://expired.badssl.com/", False),
("https://github.com/", True),
]:
display("-" * 8)
display(f"Checking {url}")
try:
with urllib.request.urlopen(url) as response:
data = response.read()
html = data.decode('utf8')
assert "<head>" in html[:600]
if expected_success:
display(f"Checking {url} - OK")
else:
error(f"Checking {url} - FAILED - should have raised an exception")
except Exception as exc:
if expected_success:
error(f"Checking {url} - FAILED - unexpected exception")
traceback.print_exc()
else:
display(f"Checking {url} - OK [Expected {exc}]")
Expected output:
--------
Checking https://data.kitware.com
Checking https://data.kitware.com - ok
--------
Checking https://www.httpvshttps.com/
Checking https://www.httpvshttps.com/ - ok
--------
Checking https://slicer.org/
Checking https://slicer.org/ - ok
--------
Checking https://expired.badssl.com/
Checking https://expired.badssl.com/ - ok [Expected <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)>]
--------
Checking https://github.com/
Checking https://github.com/ - OK