运行 python --version 命令的脚本打印得太早

运行 python --version 命令的脚本打印得太早

我有一个错误处理程序脚本,它在失败时显示我的重要环境变量(为了便于阅读,我在回显字符串中添加了一些内容Enter,完整的行添加到了问题的末尾)

echo -e "--- failed at line $1 in function $2\nvirtual env = 
$(echo ${VIRTUAL_ENV})\ncurrent dir = ${PWD}\nbranch = $(git status | head
 -1)\ngit commit = $(git log -1 | tr '\n''\t')\npip version = $(pip -
V)\nPy version = $(python --version)\nhostname = $(logname)@$(hostname)\n"

除了 python --version 部分之外,我得到了一个很好的结果:

Python 2.7.12  <--- why is this here?
--- failed at line 186 in function my_func
virtual env = 
current dir = /home/bla/blabla/foo
branch = On branch goo
git commit = commit ### Author: ... 
pip version = pip 18.1 from /usr/local/lib/python2.7/dist-packages/pip-18.1-py2.7.egg/pip (python 2.7)
Py version =  <----- instead of here
hostname = X@Y

我的实际函数不会立即使用 echo。我还调用tput setaf&&tput sgr0来修改颜色。python 行(第一行)没有颜色,而其他行都有颜色……


"--- failed at line $1 in function $2\nvirtual env = $(echo ${VIRTUAL_ENV})\ncurrent dir = ${PWD}\nbranch = $(git status | head -1)\ngit commit = $(git log -1 | tr '\n''\t')\npip version = $(pip -V)\nPy version = $(python --version)\nhostname = $(logname)@$(hostname)\n"

答案1

感谢 @steeldriver(顺便说一句,乐队不错)的评论。一旦我确认它确实打印到 stderr,修复就更容易了 - 只需将 stderr 重定向到命令的 stdout。即Py version = $(python --version 2>&1)

还要感谢 @pLumo 的评论,这个错误(打印到 stderr 而不是 stdout)已在 python 3.4 及更高版本中修复

相关内容