is_connectable.py
import platform, subprocess
def is_connectable(host: str = "pypi.org", n: int = 1) -> bool:
"""ホストにpingが通るかどうかを確認する
Args:
host (str): 対象ホスト. Defaults to "pypi.org".
n (int): pingの試行回数. Defaults to 1.
Returns:
bool: pingが通るかどうか
"""
system = platform.system()
if system == "Windows":
code = ["ping", "-n", str(n), host]
elif system in {"Linux", "Darwin"}: # Linux や macOS で対応
code = ["ping", "-c", str(n), host]
else:
raise ValueError(f"Unsupported OS: {system}")
try:
subprocess.run(code, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
return True
except subprocess.CalledProcessError:
return False