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

Python调用subprocess执行top检测进程时遇tty获取失败错误求助

解决top命令"failed tty get"错误的方案

错误原因

top默认以交互式模式运行,需要绑定终端(tty),但subprocess启动的进程默认没有分配tty,所以会抛出这个错误。

方案1:使用top的批量模式

给top加上-b参数启用批量输出模式,让它非交互式运行(无需tty),同时用-n 1让top只执行一次输出,避免持续占用资源:

import subprocess
import time

def check_lsd_running():
    # 执行批量模式的top,捕获输出并检查是否存在lsd进程
    result = subprocess.run(
        ["top", "-b", "-n", "1", "-c"],
        capture_output=True,
        text=True
    )
    return "lsd" in result.stdout.lower()

# 每秒检测一次,直到进程结束
while check_lsd_running():
    time.sleep(1)

print("Finished")

参数说明:

  • -b:启用批量模式,非交互式运行,无需tty
  • -n 1:仅执行一次top输出后退出
  • -c:显示完整命令行,避免进程名截断导致漏检
  • time.sleep(1):降低检测频率,减少系统资源消耗

方案2:用pgrep直接检测进程(集群支持时优先用)

如果集群允许使用pgrep命令,这种方式比top更高效,直接检测进程是否存在:

import subprocess
import time

def check_lsd_running():
    try:
        # pgrep找到进程返回0,没找到返回非0
        subprocess.run(
            ["pgrep", "-i", "lsd"],
            check=True,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL
        )
        return True
    except subprocess.CalledProcessError:
        return False

while check_lsd_running():
    time.sleep(1)

print("Finished")

参数说明:

  • -i:忽略大小写匹配进程名
  • 重定向stdout和stderr到/dev/null,避免冗余输出

内容的提问来源于stack exchange,提问作者Ajith MS

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:33:30