批处理中Python脚本输出重定向:控制台+文件双输出及替代方案
批处理命令重定向解决方案
一、将脚本所有输出(stdout+stderr)同时输出到控制台和文件
批处理原生没有tee命令,但可以借助PowerShell的Tee-Object实现需求,命令如下:
python GeneAll.py --var VARIANT_%VAR_ASD% 2>&1 | powershell -Command "$input | Tee-Object -FilePath output.log"
2>&1:将标准错误(stderr)重定向到标准输出(stdout),合并两个输出流- 管道后的PowerShell命令会把合并后的内容同时输出到控制台,并写入
output.log文件
如果你的系统安装了Git Bash、Cygwin等工具,也可以直接用原生tee命令:
python GeneAll.py --var VARIANT_%VAR_ASD% 2>&1 | tee output.log
二、仅将stdout输出到文件,stderr同时输出到控制台和文件
通过分别重定向两个输出流实现,命令如下:
python GeneAll.py --var VARIANT_%VAR_ASD% > stdout.log 2> >(powershell -Command "$input | Tee-Object -FilePath stderr.log")
> stdout.log:将标准输出(stdout)直接写入stdout.log文件,不显示在控制台2> >(...):将标准错误(stderr)传入PowerShell的Tee-Object,同时输出到控制台和stderr.log文件
也可以用另一种简化写法(需确保cmd支持进程替换):
python GeneAll.py --var VARIANT_%VAR_ASD% 2>&1 1>stdout.log | tee stderr.log
2>&1:将stderr重定向到stdout1>stdout.log:将原stdout写入文件(注意顺序,必须在2>&1之后,否则stderr会被错误重定向到文件)- 管道后的
tee会把stderr内容输出到控制台和stderr.log
内容的提问来源于stack exchange,提问作者Grigori Rasputin
相关产品推荐
相关产品推荐

