捕获/静音stdout/stderr输出。
OutputCatcher的Python项目详细描述
提供一个上下文管理器,用于捕获/抑制来自 sys.stderr和sys.stdout(stdoutcatcher,stderrcatcher)。阿尔索 提供从进程收集stdout和stderr的简单方法 同时可选地将stdin作为str或bytes管道发送到进程。
API
stdoutcatcher/stderrcatcher
StdOutCatcher(escaped=False,max_length=0)
这将禁止通过sys.stdout或 sys.stderr,并将其保存在属性中以备将来使用。
参数
- escaped:如果truthy,则使用repr()对输出进行“编码”,但是 没有引号。默认值:False
- max_length:如果非零,最终输出将不会超过 max_length。一旦到达max_length,则进一步write() 呼叫将被忽略。默认值:0
用法
fromoutputcatcherimportStdErrCatcher,StdOutCatcher# Catching stdoutwithStdOutCatcher()asfakeout:print('This is a test. you shouldn\'t see it right away.')print('Captured stdout: {}'.format(fakeout.output))# Catching stderrwithStdErrCatcher()asfakeerr:print('Testing stderr output.',file=sys.stderr)print('Captured stderr: {}'.format(fakeerr.output))
处理输出
ProcessOutput(args,stdin_data=None,timeout=None,**popenkwargs)
这将使用subprocess.Popen运行外部进程并收集 将来属性中的stdout和stderr输出 使用。stdin通过提供 在初始化期间将数据作为str或bytes。
使用要运行的命令初始化ProcessOutput对象后,以及 可选的stdin输入数据,它可以用作上下文管理器或 必须调用run()方法。
timeout在返回 输出。
注意:从python 3.5开始, subprocess.run() 可以通过input参数和 subprocess.CompletedProcess 返回值。尽管ProcessOutput确实为 在收到输出时对其进行迭代(iter_stdout,并且 iter_stderr)。
参数
- args:命令参数,与subprocess.popen相同。
- stdin_data:要作为stdin发送到命令的str或字节。违约: None
- timeout:收集数据后等待进程的时间。违约: None
- **popenkwargs:popen()的任何额外Kwargs。stdin, stdout和stderr被忽略。
用法
fromoutputcatcherimportProcessOutput# Basic usage:withProcessOutput(['ls'])asp:print(p.stdout.decode())# Checking for stdout and stderr:withProcessOutput(['ls','/totally_nonexistent_dir'])asp:ifp.stdout:print('Wow, it really does exist: {}'.format(p.stdout.decode()))else:print(p.stderr.decode())# Without a context manager:p=ProcessOutput(['ls'])stdout,stderr=p.run()# Sending stdin data to a process:stdin_data='Hello cat!'withProcessOutput(['cat'],stdin_data=stdin_data)asp:assertp.stdout.decode()==stdin_data# cat received the data, and piped it back.print(p.stdout.decode())# Iterating over stdout data:p=ProcessOutput(['ls'])forlineinp.iter_stdout():print(line)