Python For循环未遍历列表sys.argv

问题描述

我试图通过在运行脚本的命令行参数中获取主机名来创建4次ping服务器的功能

我的问题是将ping google.com,但使用sys.argv创建的列表中没有其他内容。 我只是使用可ping的主机名来测试脚本。

$ python3 pingy.py google.com youtube.com dummy.com

server_list = sys.argv[1:]

def ping(hosts):
  """
  Ping the host. If it is not pingable then break the script.
  """
  cmd = 'ping'
  # Ping machine 4 times.
  counter = 0
  for host in hosts:
    temp = subprocess.Popen([cmd,'-c 4',host],stdout = subprocess.PIPE)
    output = str(temp.communicate())
    output = output.split("\n")
    output = output[0].split('\\')
    for count in output:
      if 'icmp_seq' in count:
        counter = counter + 1
    if  int((counter / 4) * 100) < 75:
      return '{} is less than 75% pingable'.format(host)
    return '{} is ping-able. Attempting to SSH into the machine.'.format(host)

print(ping(server_list))

example output:
dummy@dummy$ python3 cpu_eval.py google.com youtube.com cnn.com
 google.com is ping-able. Attempting to SSH into the machine.

解决方法

您的函数在第一次迭代后返回值google.com is ping-able. Attempting to SSH into the machine.

也许尝试将每个主机的输出存储在列表中,然后在所有迭代之后返回列表。