Python调用docker run出现write /dev/stdout: broken pipe报错如何解决
报错原因
这个报错和docker本身无关,是-t参数和os.popen的调用逻辑冲突导致的:
docker run的-t参数会给容器分配伪终端,进程默认会尝试向绑定的终端输出内容os.popen启动子进程后你没有读取管道输出,Python执行完该行代码后会直接关闭管道,docker进程尝试向stdout写内容时管道已经断开,就会抛出write /dev/stdout: broken pipe报错。
解决方案
方案1(最简便):删除docker命令的-t参数
你运行的mosquitto_pub是非交互式命令,完全不需要分配伪终端,直接删掉-t即可:
import os os.popen(f'docker run --rm --link mosquitto-server ruimarinho/mosquitto mosquitto_pub -h mosquitto-server -t "test_topic" -m "{message}"')
方案2:显式读取popen输出后关闭管道
如果必须保留-t参数,就完整读取管道输出后再关闭,避免管道提前断开:
import os p = os.popen(f'docker run --rm -t --link mosquitto-server ruimarinho/mosquitto mosquitto_pub -h mosquitto-server -t "test_topic" -m "{message}"') # 读取所有输出(即使是空内容) output = p.read() # 显式关闭管道 ret_code = p.close()
方案3(最规范):改用subprocess模块替代os.popen
os.popen是老旧的进程管理API,官方更推荐用subprocess,可以直接将输出丢弃到空设备,完全不会产生终端报错:
import subprocess subprocess.run( f'docker run --rm --link mosquitto-server ruimarinho/mosquitto mosquitto_pub -h mosquitto-server -t "test_topic" -m "{message}"', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL )
内容的提问来源于stack exchange,提问作者bmrki
相关产品推荐
相关产品推荐

