我正在尝试将脚本的stderr重定向到变量,以便在if/else
语句中使用它。我需要的是根据stderr以某种方式表现的程序。
我找到this post使用StringIO可能符合我的需要,但我无法弄清楚如何使它重定向stderr。我确信它很容易,但我对python很新,任何详细的帮助都会非常感激。
谢谢!
达尼
答案 0 :(得分:2)
为了在'hack'之后拦截对stderr的写入:
import sys
STDERR = ''
def new_stderr(old):
def new(*args):
# put your code here, you will intercept writes to stderr
print('Intercepted: ' + repr(args))
global STDERR # add new write to STDERR
STDERR += args[0]
old(*args)
return new
sys.stderr.write = new_stderr(sys.stderr.write)
对stderr的所有写入都将存储在STDERR变量
中答案 1 :(得分:0)