使 Yum API 输出静音

Silencing Yum API Output

我正在寻找 "silence" python 中 yum API 的调试级别。例如,我将两个 yum 命令分配给如下变量;

import yum
yb = yum.YumBase()

yum_conf = yb.conf.config_file_path
package_list = yb.doPackageLists(pkgnarrow='updates', patterns='', ignore_case=True)

当 运行 脚本返回时,它为 CentOS 7 返回以下内容:

Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirror.sov.uk.goscomb.net
* extras: mirror.sov.uk.goscomb.net
* updates: mirror.sov.uk.goscomb.net

然后在 CentOS 6 上:

Loaded plugins: fastestmirror
Determining fastest mirrors

我不想要这种冗长的打印。我认为这与日志记录级别有关,但我对如何更改它存在分歧。

上下文管理器的完美场景。这要么被打印到 stdout 要么 stderr,下面的技术适用于任何一个。

import io
import contextlib
import yum

f = io.StringIO()
with contextlib.redirect_stdout(f):  # or redirect_stderr... or both
    ''' All the output in here is redirected to the filelike object, f '''

    yb = yum.YumBase()
    yum_conf = yb.conf.config_file_path
    package_list = yb.doPackageLists(pkgnarrow='updates', patterns='', 
        ignore_case=True)
s = f.getvalue()  # s now contains all that output you didn't want

你只需要这两行,

  yb.preconf.debuglevel = 0
  yb.preconf.errorlevel = 0

例如,python 脚本,getpkg.py 看起来类似于以下内容:

  import yum

  yb = yum.YumBase()
  yb.preconf.debuglevel = 0
  yb.preconf.errorlevel = 0
  yb.install(name='emacs-nox')
  yb.resolveDeps()
  yb.processTransaction()

结果:

~]# python getpkg.py 
Installing: 1:perl-parent-0.225-244.el7.noarch 0/8868 [1/32]
Installing: 1:perl-parent-0.225-244.el7.noarch 144/8868 [1/32]
Installing: 1:perl-parent-0.225-244.el7.noarch 2649/8868 [1/32]
Installing: 1:perl-parent-0.225-244.el7.noarch 5686/8868 [1/32]
....
....