1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

指定のホストへpingが通るかチェック

Posted at
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

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?