PyCharm提示函数内start_time代码不可达,代码却正常运行的原因
PyCharm提示代码不可达的原因分析
你编写的网络连接检测代码放入函数后,PyCharm提示start_time = time.time()这一行代码不可达,但程序实际能正常运行,原因如下:
问题代码
from time import time, sleep import os def something(): while True: sleep(2 - time() % 2) ip_list = ['8.8.8.8'] for ip in ip_list: response = os.popen(f"ping {ip}").read() if "Received = 4" in response: print(f"UP {ip} Ping Successful") _connected = True print(_connected) else: print(f"DOWN {ip} Ping Unsuccessful") _connected = False print(_connected) start_time = time.time() seconds = 1 while True: current_time = time.time() elapsed_time = current_time - start_time if elapsed_time > seconds: print("Finished iterating in: " + str(int(elapsed_time)) + " seconds") break something()
警告原因
函数开头的while True:是无限循环,里面没有任何break、return或抛出异常的逻辑能终止这个循环。程序运行时会一直卡在这个循环里反复执行网络检测,永远不会走到循环后面的start_time = time.time()及后续代码。
PyCharm的静态代码分析能识别出这个逻辑:循环没有出口,后续代码永远无法被执行,所以给出“不可达”的警告。你觉得代码能正常运行,是因为程序一直在第一个循环里工作,根本没机会触发到后面未执行的代码段,警告本身是完全准确的。
解决建议
如果需要让后面的计时代码也能执行,你可以:
- 给第一个无限循环添加退出条件,比如检测到网络连接状态变化后
break,或者设置运行时长限制; - 使用多线程,把网络检测和计时逻辑分开在不同线程中执行,避免互相阻塞。
内容的提问来源于stack exchange,提问作者TxTechnician
相关产品推荐
相关产品推荐

