You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 21:03:09