捕获/静音stdout/stderr输出。

OutputCatcher的Python项目详细描述


提供一个上下文管理器,用于捕获/抑制来自 sys.stderrsys.stdout(stdoutcatcher,stderrcatcher)。阿尔索 提供从进程收集stdout和stderr的简单方法 同时可选地将stdin作为strbytes管道发送到进程。

API

stdoutcatcher/stderrcatcher

StdOutCatcher(escaped=False,max_length=0)

这将禁止通过sys.stdoutsys.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运行外部进程并收集 将来属性中的stdoutstderr输出 使用。stdin通过提供 在初始化期间将数据作为strbytes

使用要运行的命令初始化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。stdinstdoutstderr被忽略。

用法

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)

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
字典java cassandra对象映射注释   java定制Solr TokenFilter lemmatizer   字符串从Java文件中读取windows文件名   java如何在Windows上设置StanfordCorenlp服务器以返回文本   java axis2“意外的子元素值”   java使用POI HSSF获取错误   多线程Java等待计时器线程完成   java ForkJoinPool BuffereImage处理风格   从java代码运行Python脚本   java将字节[]转换为短[],使每个短元素包含13位数据   java如何为swing jframe应用程序将代码划分为类   java使用okhttp更改baseurl   java AlertDialog。建设者setView导致堆栈溢出错误   java如何在特定的radius 安卓 studio中接收地址列表?