如何在Python中屏蔽终端/控制台的bash命令输出
解决方案
通过subprocess模块重定向输出
执行bash命令时,利用subprocess模块的参数将标准输出(stdout)和标准错误(stderr)重定向到subprocess.DEVNULL,直接丢弃bash命令的所有输出:import subprocess # 屏蔽命令的标准输出和错误输出 subprocess.run(["ls", "-l"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # 若需将错误输出合并到标准输出一起屏蔽,可使用stderr=subprocess.STDOUT subprocess.run(["bash", "your_script.sh"], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)在bash命令中直接重定向到/dev/null
借助bash自身的重定向语法,在命令末尾添加> /dev/null 2>&1,将所有输出导向空设备:import subprocess # 注意:使用shell=True需警惕命令注入风险,若命令包含用户输入请避免使用 subprocess.run("bash your_script.sh > /dev/null 2>&1", shell=True)捕获输出但不打印
如果后续可能需要调用输出内容,但当前不想显示在终端,可通过capture_output=True捕获输出到变量中,不执行打印操作即可:import subprocess # 捕获输出到result对象,不主动打印则不会刷屏终端 result = subprocess.run(["ls", "-l"], capture_output=True, text=True) # 后续可通过result.stdout、result.stderr访问输出内容
内容的提问来源于stack exchange,提问作者brownser
相关产品推荐
相关产品推荐

