重定向 stderr 并保留 stdout
redirect stderr and keep stdout
我想编写一个 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)。
And: 如果有人有更聪明(和稳定)的想法来交出计算结果,将不胜感激。
预期输出:
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,并将 stderr 存储在一个变量中,您可以在脚本末尾回显该变量。
所以尝试这样的事情:
#!/bin/bash
line="+++++++++++++++++++++++++"
python pyscript.py 3>&2 2>&1 1>&3 | read errormessage
echo "$line"
echo "Error variable is ${errormessage}"
这应该会正常打印您的标准输出并在最后打印标准错误。
我想编写一个 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)。
And: 如果有人有更聪明(和稳定)的想法来交出计算结果,将不胜感激。
预期输出:
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,并将 stderr 存储在一个变量中,您可以在脚本末尾回显该变量。 所以尝试这样的事情:
#!/bin/bash
line="+++++++++++++++++++++++++"
python pyscript.py 3>&2 2>&1 1>&3 | read errormessage
echo "$line"
echo "Error variable is ${errormessage}"
这应该会正常打印您的标准输出并在最后打印标准错误。