python ping 连接_在Python中ping服务器

b700ec0e089a602c40c9bafe6397f6d0.png

慕粉4167745

此功能适用于任何操作系统(Unix,Linux,macOS和Windows)Python 2和Python 3编辑:由@radato os.system取代subprocess.call。通过@Borissubprocess.run()如果您使用的是Python 3.5+,则文档建议使用。import platform    # For getting the operating system nameimport subprocess  # For executing a shell commanddef ping(host):

    """

    Returns True if host (str) responds to a ping request.

    Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.

    """

    # Option for the number of packets as a function of

    param = '-n' if platform.system().lower()=='windows' else '-c'

    # Building the command. Ex: "ping -c 1 google.com"

    command = ['ping', param, '1', host]

    return subprocess.call(command) == 0请注意,根据Windows上的@ikrase,True如果出现Destination Host Unreachable错误,此功能仍将返回。说明该命令适用ping于Windows和类Unix系统。选项-n(Windows)或-c(Unix)控制在此示例中设置为1的数据包数。platform.system()返回平台名称。防爆。'Darwin'在macOS上。subprocess.call()执行系统调用。防爆。subprocess.call(['ls','-l'])。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值