Python For循环不在列表上迭代(sys.argv)

Python For循环不在列表上迭代(sys.argv),python,ping,sys,Python,Ping,Sys,我试图创建一个函数,通过在运行脚本的命令行参数中使用主机名来ping服务器4次 我的问题是将ping google.com,但在使用sys.argv创建的列表中没有其他内容。 我只是使用pingable主机名来测试脚本 $python3 pingy.py google.com youtube.com dummy.com server_list = sys.argv[1:] def ping(hosts): """ Ping the host. If it

我试图创建一个函数,通过在运行脚本的命令行参数中使用主机名来ping服务器4次

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

$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.
server\u list=sys.argv[1:]
def ping(主机):
"""
Ping主机。如果主机不可Ping,请中断脚本。
"""
cmd='ping'
#Ping机器4次。
计数器=0
对于主机中的主机:
temp=subprocess.Popen([cmd'-c4',host],stdout=subprocess.PIPE)
输出=str(临时通信())
输出=输出。拆分(“\n”)
输出=输出[0]。拆分(“\\”)
对于输出计数:
如果计数中有“icmp_seq”:
计数器=计数器+1
如果整数((计数器/4)*100)<75:
返回“{}小于75%可ping”。格式(主机)
返回{}是可ping的。正在尝试SSH到计算机中。“.format(主机)
打印(ping(服务器列表))
示例输出:
dummy@dummy$python3 cpu_eval.py google.com youtube.com cnn.com
google.com可以ping。正在尝试SSH到计算机中。

您的函数在第一次迭代后返回值
google.com可ping。正在尝试SSH连接到计算机。


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

阅读有关调试代码的提示。您在第一个循环结束时从函数返回。您是对的。这是主要问题。在这一点之后,我遇到了一些其他问题,但要点是,我没有将主机添加到列表中,而是使用了字典。值为{'host':ping counter}。谢谢你的帮助。