使用subprocess.run导致脚本挂起,跨Python版本环境求助
解决Linux环境下subprocess调用ping挂起的问题
核心问题:你混淆了Windows和Linux的ping命令参数
本地Windows环境中,ping用-n指定发包次数;但在Linux环境里,-n是禁用DNS解析的参数,指定次数要用-c。你在Linux服务器上用-n 5,相当于让ping无限发送数据包,这就是脚本挂起的根本原因。修正后的代码(兼容跨平台,shell=False):
import subprocess import platform def check_host_reachability(ip): # 根据操作系统自动选择ping参数 count_param = "-n" if platform.system().lower() == "windows" else "-c" # 执行ping命令,shell=False,Python3.7+支持text=True直接返回字符串 ping_result = subprocess.run( ["ping", count_param, "5", ip], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=10 # 合理设置超时,避免异常挂起 ) # 返回执行状态码和输出内容 return ping_result.returncode, ping_result.stdout补充说明:
- 加
text=True是为了让subprocess直接返回字符串,不用手动对stdout做decode操作,Python3.7及以上版本都支持 - timeout设置为10秒足够覆盖5次ping的执行时间,避免遇到异常网络状况时脚本挂起
- 保持
shell=False符合你的需求,同时避免了shell=True带来的输出格式问题和安全风险
- 加
内容的提问来源于stack exchange,提问作者whitemilkfish
相关产品推荐
相关产品推荐

