使用Python ping网站时必须指定IP地址

时间:2019-03-19 03:28:06

标签: python ip ping

因此,我试图对Microsoft或Google之类的网站执行ping命令并打印出结果,但是当我运行脚本时,它只是说:“必须指定IP地址。”。我尝试环顾四周,以了解为什么会发生这种情况,但似乎无法缩小解决方案的范围。

这是我的代码:

import subprocess

print('Ping www.microsoft.com')
print()
address = 'www.microsoft.com'
subprocess.call(['ping', '-c 3', address])

我做错什么了吗?如果是这样,任何帮助或解释将不胜感激!

1 个答案:

答案 0 :(得分:1)

要显示子流程调用的输出,可以使用check_output方法:REST API

import subprocess

def ping():
  print('Ping www.microsoft.com')
  print()
  address = 'www.microsoft.com'
  print(subprocess.check_output(['ping', '-c', '3', address]).decode())

ping()

输出:

Ping www.microsoft.com

PING e13678.dspb.akamaiedge.net (23.53.160.151) 56(84) bytes of data.
64 bytes from a23-53-160-151.deploy.static.akamaitechnologies.com (23.53.160.151): icmp_seq=1 ttl=55 time=83.6 ms
64 bytes from a23-53-160-151.deploy.static.akamaitechnologies.com (23.53.160.151): icmp_seq=2 ttl=55 time=83.5 ms
64 bytes from a23-53-160-151.deploy.static.akamaitechnologies.com (23.53.160.151): icmp_seq=3 ttl=55 time=83.7 ms

--- e13678.dspb.akamaiedge.net ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2003ms
rtt min/avg/max/mdev = 83.567/83.648/83.732/0.067 ms