如何从元组中ping?

时间:2016-10-12 14:00:10

标签: python

如何从元组中ping主机列表并将响应存储到另一个元组列表中?

我知道如何ping单个主机:

hostname = "10.0.0.250" #example

response = os.system("ping -c 1 " + hostname)

2 个答案:

答案 0 :(得分:2)

在给定主机名元组的情况下,你可以简单地使用列表理解 / 生成器表达式(用于元组):

hostnames = ("10.0.0.250", "10.0.0.240", ...)
responses = tuple(os.system("ping -c 1 " + h) for h in hostnames)

答案 1 :(得分:1)

hostnames = ["10.0.0.1", "10.0.0.2"]
# Can use a tuple instead of list.
responses = [os.system("ping -c 1 " + hostname) for hostname in hostnames]
# You can enwrap the list comprehension in a call to the tuple() function
# to make `responses` a tuple instead of list.