我该如何解决IndexError问题,以便在病房结束后可以连续运行脚本?

问题描述

我是python的新手,我了解了旨在检查网络的新自动功能,并说当您输入ip的人到达时,我一开始就修复了一些错误,但现在我陷入了困境。

import sys
import subprocess 
import os
from decouple import config

IP_NETWORK = config('IP_NETWORK')
IP_DEVICE = config('IP_DEVICE')

proc = subprocess.Popen(["ping",IP_NETWORK],stdout=subprocess.PIPE)
while True:
  line = proc.stdout.readline()
  if not line:
    break
  #the real code does filtering here
  connected_ip = line.decode('utf-8').split()[3]

  if connected_ip == IP_DEVICE:
      subprocess.Popen(["say","New just connected to the network ! "])

我试图查看拆分的工作原理,但我不理解

错误

file.py",line 15,in <module>
connected_ip = line.decode('utf-8').split()[3]
IndexError: list index out of range

解决方法

也许line.decode('utf-8')的输出少于4个部分? 在这种情况下,将引发out of range错误。