【问题标题】:redirect stderr and keep stdout [duplicate]重定向标准错误并保留标准输出[重复]
【发布时间】:2019-08-09 13:32:46
【问题描述】:

我想编写一个bash 脚本,它应该调用多个python 脚本。 在python 脚本中有几条我不允许更改的打印消息。我想将计算的最终状态解析为我的 bash 脚本,以决定下一步该做什么。 我的计划是构建python 文件,例如:

import sys

print('this is just some print messages within the script')
print('this is just some print messages within the script')

sys.stderr.write('0 or 1 for error or sucessfull')

并在 bash 脚本中重定向 stderr(但仍将 print 函数的输出保留在终端上)

errormessage="$(python pyscript.py command_for_redirecting_stderr_only)"

有人可以帮我只重定向stderr吗?我发现的所有解决方案都不会保留print 函数的输出(大多数人将stdout 设置为null)。

并且:如果有人有更聪明(更稳定)的想法来交出计算结果,将不胜感激。

预期输出:

pyscript.py

import sys
print('this is just some print messages within the script')
print('this is just some print messages within the script')
sys.stderr.write('0 or 1 for error or sucessfull')

bashscript.sh

#!/bin/bash
LINE="+++++++++++++++++++++++++"
errormessage="$(python pyscript.py command_for_redirecting_stderr_only)"
echo $LINE
echo "Error variable is ${errormessage}"

当我调用bash bashscript.sh时输出:

this is just some print messages within the script
this is just some print messages within the script
+++++++++++++++++++++++++
Error variable is 0/1

【问题讨论】:

  • 也许我正在监督一些事情,但他们在那个提议的答案中,当你想要将 stderr 重定向到一个变量并将 stdout 保留在终端上时,正是缺少这种情况
  • 已回答here

标签: bash stdout stderr


【解决方案1】:

您可以交换 stderr 和 stdout 并将 stderr 存储在一个变量中,您可以在脚本末尾回显该变量。 所以尝试这样的事情:

#!/bin/bash
line="+++++++++++++++++++++++++"
python pyscript.py 3>&2 2>&1 1>&3 | read errormessage
echo "$line"
echo "Error variable is ${errormessage}"

这应该像平常一样打印您的标准输出并在最后打印标准错误。

【讨论】:

  • 感谢您的回答!不幸的是,当我运行脚本时,变量 $errormessage 是空的。
  • 对不起,你得把 (python pyscript.py 3>&2 2>&1 1>&3) 周围的括号去掉,我的错
  • 不知何故它仍然是空的......但是 errormessage=$(python pyscript.py 3>&2 2>&1 1>&3) 工作......非常感谢
  • 管道末端的 read 可以在子外壳中运行。这是一个常见问题解答; stackoverflow.com/questions/13763942/…
猜你喜欢
  • 1970-01-01
  • 2012-08-15
  • 1970-01-01
  • 2014-03-22
  • 2010-10-12
  • 2011-10-11
  • 1970-01-01
相关资源
最近更新 更多