Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

How can I save the standard Yum output to a variable from the Python Yum API?

For example:

>>> import yum
>>> y = yum.YumBase()
>>> x = {'release': '11.el7', 'epoch': '', 'version': '3.10', 'arch': 'x86_64', 'name': 'PyYAML'}
>>> y.install(**x)
Package PyYAML-3.10-11.el7.x86_64 is obsoleted by python2-pyyaml-5.1.2-1.0.1.el7.x86_64 which is already installed
[]

What's returned here is the empty list. Is there a clean way to assign the standard yum message to a variable?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Seems like this messages are generated via logging. So one way to get this messages is to redirect the output of the function call to a buffer.

>>> import logging
>>> import io
>>> from contextlib import redirect_stderr
>>>
>>> def install():
...     logging.warning("Some Message")
...     return []
...
>>> f = io.StringIO()
>>>
>>> with redirect_stderr(f):
...     result = install()
...
>>> print("Functon Result: ", result)
Functon Result:  []
>>> print("Function messages::", f.getvalue())
Function Warning messages:: WARNING:root:Some Message

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...