使用shell命令包装嘈杂的python脚本并使用sed删除特定行时出现问题

2024-10-03 02:46:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用一个python脚本,它基于完全正常的坏测试证书输出许多警告/错误(转到stderr)。基于几个SO帖子,我找到了一种运行脚本并忽略select stdout、stderr行的方法,但它很麻烦:

runThing 3>&1 1>&2 2>&3 3>&- | grep -r 's/Insecure/'
 OR 
runThing 3>&1 1>&2 2>&3 3>&- | sed 's/Insecure/g'

两者都会过滤掉很多行,比如:

 /Users/xxx/.blah/lib/python2.7/site-   packages/requests/packages/urllib3/connectionpool.py:791: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html  InsecureRequestWarning)

但是sed有这个错误: sed:1:“s/unsecure/g”:正则表达式中未终止的替换

在经常使用的一行末尾添加了很多内容(真正的runThing有命令和参数),因此我尝试生成如下命令:

runThingClean() { command runThing "$@" > /dev/null 3>&1 1>&2 2>&3 3>&- | sed 's/Insecure/g' & }

当我运行这个时,它现在无法过滤(并显示错误是sed):

 sed: 1: "s/Insecure/g": unterminated substitute in regular expression

有人能帮我修改这个命令吗?你知道吗

提前谢谢。。你知道吗


Tags: 命令脚本警告soispackages错误stderr
2条回答

该错误意味着您没有正确关闭sed中的s。对于s,它应该是s/regex/substitution/g

如果您试图删除Insecure或替换:

sed 's/Insecure/YOUR_SUBSTITUTION/g'

如果试图仅显示带有Insecure的行:

sed -n '/Insecure/p'

完全不要这样做:只要告诉Python不要首先打印警告,然后就不需要过滤掉它们。你知道吗

python -W ignore yourprogram ...

或者,考虑修改调用相关组件的代码,以抑制调用站点上的警告,如given in the Python documentation

import warnings
with warnings.catch_warnings():
    warnings.simplefilter('ignore')
    urllib3.doTheThingThatCausedTheWarning(...)

最后,如果你真的想把它作为一个过滤器来处理,只需要使用grep -v Insecuresed就可以了。你知道吗

sh -c 'printf "%s\n" "stderr: keep" "stderr: Insecure" >&2; echo "stdout"' \
  3>&1 1>&2 2>&3 3>&- | grep -v Insecure 3>&1 1>&2 2>&3 3>&-

所有这些重定向所做的就是在grep之前和之后交换stdout和stderr两次以恢复它们。让我们看看它是如何工作的:

  • FD 1(原始标准输出)复制到FD 3(作为备份)
  • FD 2(原始标准)复制到FD 1(因此可以过滤)
  • fd3(原始stdout的备份)被复制到fd2(现在存储在stderr中)
  • FD3关闭,因为交换完成后不再需要它。你知道吗

相关问题 更多 >