bash - 重定向标准错误并保留标准输出
问题描述
我想编写一个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)。
并且:如果有人有更聪明(更稳定)的想法来交出计算结果,将不胜感激。
预期输出:
脚本.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')
脚本文件
#!/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}"
这应该正常打印您的标准输出并在最后打印标准错误。
推荐阅读
- android - ArrayAdapter:搜索类名本身而不是用户
- c - 关于在链表末尾添加元素的问题
- python - 关于 Pymongo 多处理
- opencv - 从 2D 坐标获取 3D 坐标
- python - Python 解码和编码
- python - 用 scrapy 从 wordpress 网站上抓取
- c++ - 移除进度条边框
- javascript - 如何仅从我关注的用户那里检索帖子以及如何在实时数据库中构建数据?我正在使用 React 和 Firebase
- python - 在 excel 文件表中插入数据框,但 df.to_excel 正在删除其他 excel 文件表
- r - 如何将情感分析结果(dfm)与 Quanteda 中的原始 readtext 对象合并?