How to capture stdout to string using invoke.run() in Python
This example showcases how to capture stdout to a string instead of printing it to system stdout:
The basic trick is to initialize a StringIO
(a file-like object where pyinvoke can write the stdout from the sub-process to) and pass it to the out_stream
argument of invoke.run()
import invoke
from io import StringIO
outStream = StringIO()
result = invoke.run("wg genkey", out_stream=outStream)
stdout_str = outStream.getvalue()
print("Result: ", stdout_str)
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow