沉默Yum API输出

时间:2017-04-25 20:21:54

标签: python api yum

我期待"沉默" 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

我不想要这种冗长的打印级别。我认为这与日志记录级别有关,但我正处于如何改变它的交叉路径。

2 个答案:

答案 0 :(得分:1)

您只需要这两行,

  yb.preconf.debuglevel = 0
  yb.preconf.errorlevel = 0
例如,python scipt,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]
....
....

答案 1 :(得分:0)

上下文管理器的完美场景。这可以打印到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