Sick Gaming
[Tut] 7 Easy Steps to Redirect Your Standard Output to a Variable (Python) - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Programming (https://www.sickgaming.net/forum-76.html)
+--- Forum: Python (https://www.sickgaming.net/forum-83.html)
+--- Thread: [Tut] 7 Easy Steps to Redirect Your Standard Output to a Variable (Python) (/thread-99425.html)



[Tut] 7 Easy Steps to Redirect Your Standard Output to a Variable (Python) - xSicKxBot - 05-20-2022

7 Easy Steps to Redirect Your Standard Output to a Variable (Python)

<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;365385&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend"> 5/5 – (1 vote) </div>
</div>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: How to redirect the standard output in Python and store it as a string in a variable?</p>
<p>This article will guide you through seven easy steps to solve this problem. As an overview, here’s the code in eight lines that stores the standard output in a variable <code>my_result</code>:</p>
<ol class="has-global-color-8-background-color has-background">
<li><code>from io import StringIO</code></li>
<li><code>import sys</code></li>
<li><code>tmp = sys.stdout</code></li>
<li><code><strong>my_result = StringIO()</strong></code></li>
<li><code><strong>sys.stdout = my_result</strong></code></li>
<li><code><strong>print('hello world')</strong> # output stored in my_result</code></li>
<li><code>sys.stdout = tmp</code></li>
<li><code>print(result.getvalue())</code></li>
</ol>
<p>Let’s go over those steps one by one—<strong>we’ll examine the full code for copy&amp;paste at the end of this article, so read on</strong>! <img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f440.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>Step 1: Import libraries StringIO and sys</h2>
<p>Import the two libraries <code>StringIO</code> and <code>sys</code> to access the standard output and store the string input-output stream. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from io import StringIO import sys</pre>
<p>Both modules are part of the standard library, so there is no need to install them with <a href="https://blog.finxter.com/a-guide-of-all-pip-commands/" data-type="post" data-id="90570">pip</a>!</p>
<h2>Step 2: Keep stdout in temporary variable</h2>
<p>We’ll overwrite the standard output to catch everything written to it. In order to reset your code to the normal state, we need to capture the original standard output stream by introducing a temporary variable. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">tmp = sys.stdout</pre>
<h2>Step 3: Capture standard output using a StringIO object</h2>
<p>Create a variable and assign a <code>StringIO</code> object to the variable to capture the standard output stream. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_result = StringIO()</pre>
<p>Now, this object can store everything <a rel="noreferrer noopener" href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank">printed</a> to the standard output. But we have to connect it first to the stdout!</p>
<h2>Step 4: Assign Standard Output Stream to StringIO object</h2>
<p>Assign the <code>StringIO</code> object created in the previous step to the standard output that is captured with <code>sys.stdout</code>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">sys.stdout = my_result</pre>
<h2>Step 5: Print to the standard output</h2>
<p>From this point onwards, anything that is printed using the <code><a href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank" rel="noreferrer noopener">print()</a></code> statement by any function you call in your Python script is written in the <code>StringIO</code> object referred to by variable <code>my_result</code>.</p>
<p>The following exemplifies the <code>print('hello world')</code> statement but you can do anything here:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print('hello world')</pre>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Note</strong>: No output appears on the screen anymore because the standard output is now redirected to the variable.</p>
<h2>Step 6: Clean up by redirecting stdout to Python shell</h2>
<p>Are you ready with capturing the output in the variable? Clean up by redirecting the standard output stream from the variable to the screen again.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">sys.stdout = tmp</pre>
<h2>Step 7: Get and print the string from stdout</h2>
<p>At this point, your string from the standard output is stored in the <code>StringIO</code> object in the <code>my_result</code> variable. You can access it using the <code>StringIO.getvalue()</code> method. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(result.getvalue())</pre>
<h2>Full Code</h2>
<p>Here’s the full code snippet for ease of copy&amp;paste:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Step 1
from io import StringIO
import sys # Step 2
tmp = sys.stdout # Step 3
my_result = StringIO() # Step 4
sys.stdout = my_result # Step 5
print('hello world') # Step 6
sys.stdout = tmp # Step 7
print('VARIABLE:', my_result.getvalue())
# hello world</pre>
<p>You can also check this out on our interactive Jupyter notebook so you don’t have to try in your own shell:</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://colab.research.google.com/drive/1be2NsSIYzk7CM0ahtItRLzL82m2lL1F6?usp=sharing" target="_blank" rel="noopener"><img loading="lazy" width="723" height="316" src="https://blog.finxter.com/wp-content/uploads/2022/05/image-168.png" alt="" class="wp-image-365529" srcset="https://blog.finxter.com/wp-content/uploads/2022/05/image-168.png 723w, https://blog.finxter.com/wp-content/uploads/2022/05/image-168-300x131.png 300w" sizes="(max-width: 723px) 100vw, 723px" /></a></figure>
</div>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f9e9.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Try it yourself</strong>: <a rel="noreferrer noopener" href="https://colab.research.google.com/drive/1be2NsSIYzk7CM0ahtItRLzL82m2lL1F6?usp=sharing" data-type="URL" data-id="https://colab.research.google.com/drive/1be2NsSIYzk7CM0ahtItRLzL82m2lL1F6?usp=sharing" target="_blank">Click to run in Jupyter Notebook (Google Colab)</a></p>
<p><strong>References: </strong></p>
<ul>
<li><a href="https://wrongsideofmemphis.com/2010/03/01/store-standard-output-on-a-variable-in-python/" target="_blank" rel="noreferrer noopener">https://wrongsideofmemphis.com/2010/03/01/store-standard-output-on-a-variable-in-python/</a></li>
</ul>
<p>Are you ready to up your Python skills? Join our free email academy — we’ve cheat sheets too! <img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f642.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
</div>


https://www.sickgaming.net/blog/2022/05/14/7-easy-steps-to-redirect-your-standard-output-to-a-variable-python/