Python Ping脚本集成NeoPixel LED调用colorWipe崩溃,求解决方案
问题分析与解决方案
你的脚本崩溃主要由以下几个问题导致,对应修复步骤如下:
1. 缺失time模块导入
colorWipe和theaterChase函数中使用了time.sleep(),但代码开头未导入time模块,调用时会触发NameError直接崩溃。
修复:
在导入区域添加:
import time
2. 调用colorWipe时未传入合法颜色参数
当ping响应码为0时,你需要给colorWipe传入strip对象和Color实例(比如用绿色表示主机在线),否则函数无法执行动画逻辑。
修复:
在ping_return_code函数的response == 0分支中添加调用:
# 执行绿色wipe动画表示主机在线 colorWipe(strip, Color(0, 255, 0))
3. 修复elif条件逻辑错误
原代码中elif response == 1 or 2 or 256 or 512的写法逻辑错误,会导致无论response是什么值,该分支都会触发。正确写法应该是判断response是否在指定集合中:
elif response in (1, 2, 256, 512):
4. 优化全局对象依赖(可选但推荐)
虽然strip作为全局对象可以直接调用,但更规范的方式是将其作为参数传递给相关函数,避免全局变量依赖。
示例修改:
修改verify_hosts函数接收strip参数:
def verify_hosts(host_list, strip): return_codes = dict() for hostname in host_list: return_codes[hostname] = ping_return_code(hostname, strip) return return_codes
同时更新ping_return_code的参数列表:
def ping_return_code(hostname, strip): # 原有逻辑保持不变,调用colorWipe时直接使用传入的strip参数
最后在main函数中传递strip:
verify_hosts(hosts_to_test, strip)
5. 启用退出清屏功能
原代码解析了--clear参数但未实际使用,可在main末尾添加退出处理逻辑:
def main(): hosts_to_test = ["127.0.0.1", "192.168.10.5"] verify_hosts(hosts_to_test, strip) # 处理退出清屏 try: input("Press Enter to exit...") finally: if args.clear: colorWipe(strip, Color(0, 0, 0), 10)
完整修复后的代码
import os import platform import subprocess import time # 添加time模块导入 from rpi_ws281x import PixelStrip, Color import argparse # LED strip configuration: LED_COUNT = 60 # Number of LED pixels. LED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!). LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz) LED_DMA = 10 # DMA channel to use for generating signal (try 10) LED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest LED_INVERT = False # True to invert the signal (when using NPN transistor level shift) LED_CHANNEL = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53 plat = platform.system() # Process arguments parser = argparse.ArgumentParser() parser.add_argument('-c', '--clear', action='store_true', help='clear the display on exit') args = parser.parse_args() # Create NeoPixel object with appropriate configuration. strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL) # Intialize the library (must be called once before other functions). strip.begin() # Define functions which animate LEDs in various ways. def colorWipe(strip, color, wait_ms=50): """Wipe color across display a pixel at a time.""" for i in range(strip.numPixels()): strip.setPixelColor(i, color) strip.show() time.sleep(wait_ms / 1000.0) def theaterChase(strip, color, wait_ms=50, iterations=10): """Movie theater light style chaser animation.""" for j in range(iterations): for q in range(3): for i in range(0, strip.numPixels(), 3): strip.setPixelColor(i + q, color) strip.show() time.sleep(wait_ms / 1000.0) for i in range(0, strip.numPixels(), 3): strip.setPixelColor(i + q, 0) def ping_return_code(hostname, strip): """Use the ping utility to attempt to reach the host. We send 5 packets ('-c 5') and wait 3 milliseconds ('-W 3') for a response. The function returns the return code from the ping utility. """ try: if plat == "Windows": response = subprocess.call(['ping', '-n', '5', '-W', '3', hostname], stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w')) elif plat == "Linux": response = subprocess.call(['ping', '-c', '5', '-W', '3', hostname], stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w')) print(f"Verify a host \"{hostname}\" for Network Reachability using PING Tool") print("---- Trying to Ping a Server with IPAddress ----", hostname) # Check for response status code, Ping Success code is '0' if response == 0: print("********************************************************************") print(hostname, 'is UP and reachable!') print("********************************************************************") colorWipe(strip, Color(0, 255, 0)) # 触发LED动画 elif response in (1, 2, 256, 512): # 修复条件判断逻辑 print("********************************************************************") print(hostname, 'is DOWN and No response from Server!') print("********************************************************************") print("\n") except Exception: print("********************************************************************") print(hostname, 'is DOWN and Host Unreachable!') print("********************************************************************") print("\n") return response def verify_hosts(host_list, strip): """For each hostname in the list, attempt to reach it using ping. Returns a dict in which the keys are the hostnames, and the values are the return codes from ping. Assumes that the hostnames are valid. """ return_codes = dict() for hostname in host_list: return_codes[hostname] = ping_return_code(hostname, strip) return return_codes def main(): # List of IP-address/Hosts for Ping test hosts_to_test = [ "127.0.0.1", "192.168.10.5", ] verify_hosts(hosts_to_test, strip) # 处理退出清屏 try: input("Press Enter to exit...") finally: if args.clear: colorWipe(strip, Color(0, 0, 0), 10) if __name__ == '__main__': main()
内容的提问来源于stack exchange,提问作者Danut Dobre
相关产品推荐
相关产品推荐

