Sick Gaming
[Tut] How to Assign the Result of exec() to a Python Variable? - 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] How to Assign the Result of exec() to a Python Variable? (/thread-99435.html)



[Tut] How to Assign the Result of exec() to a Python Variable? - xSicKxBot - 05-22-2022

How to Assign the Result of exec() to a Python Variable?

<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;370187&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>: Say you have an expression you want to execute using the <code>exec()</code> function. How to store the result of the expression in a Python variable <code>my_result</code>?</p>
<p>Before I show you the solution, let’s quickly recap the <code>exec()</code> function:</p>
<h2>Recap Python exec()</h2>
<p>Python’s <code>exec()</code> function executes the Python code you pass as a string or executable object argument. </p>
<p>This is called <em><strong>dynamic execution</strong></em> because, in contrast to normal <em>static </em>Python code, you can generate code and execute it at runtime. </p>
<p>This way, you can run programmatically-created Python code.</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python exec() — A Hacker’s Guide to A Dangerous Function" width="780" height="439" src="https://www.youtube.com/embed/DHpDA4QDGiU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p><strong>Related Tutorial</strong>: <a href="https://blog.finxter.com/python-exec/" data-type="URL" data-id="https://blog.finxter.com/python-exec/" target="_blank" rel="noreferrer noopener">Python’s <code>exec()</code> built-in function</a></p>
<p>Without further ado, let’s learn how you can store the result of the <code>exec()</code> function in a Python variable:</p>
<h2>Method 1: Define Variable in String Representation of Code</h2>
<p class="has-global-color-8-background-color has-background">You <em>can </em><strong>define a variable inside the <code>exec()</code> function</strong> that will then be added to the global namespace. Thus, you can access the defined variable in your code after the termination of the <code>exec()</code> expression!</p>
<p>Here’s how that works in a minimal example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">exec('my_result = 40 + 2')
print(my_result)
# 42</pre>
<p>Variable <code>my_result</code> is only defined in the string expression passed into <code>exec()</code>. You can use it in the code like it was part of the original source code.</p>
<h2>Method 2: How to Replace Value of a Variable in exec()</h2>
<p class="has-global-color-8-background-color has-background">To replace a variable defined outside the <code>exec()</code> function call, you can simply do so using an <a href="https://blog.finxter.com/string-formatting-vs-format-vs-formatted-string-literal/" data-type="post" data-id="13190" target="_blank" rel="noreferrer noopener">f-string</a> and pass the new value as the right-hand side of the assignment operator within the string representation of the code to be executed.</p>
<p>Here’s a minimal example where we overwrite the <code>old_variable</code> with the new string <code>'hello finxter'</code> by using the expression:</p>
<p><code>exec(f'old_variable = "{new_string}"')</code></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">old_variable = 'hello world'
new_string = 'hello finxter' # Replace old_old variable with new string 'hello finxter'
exec(f'old_variable = "{new_string}"') print(old_variable)
# hello finxter
</pre>
<h2>Method 3: How to Replace Global Variable in exec()?</h2>
<p>If you use the previous approach to replace a <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-use-global-variables-in-a-python-function/" data-type="post" data-id="14662" target="_blank">global variable</a> defined outside the <code>exec()</code> expression that is called in a local context, the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-in-place-assignment-operators/" data-type="post" data-id="33217" target="_blank">assignment operator</a> will work on a <strong>local alias variable</strong>. </p>
<p><strong>The global variable to be replaced will remain the same!</strong></p>
<p>This can be seen in the following code example, where the global <code>old_variable</code> is not replaced with the new string <code>'hello finxter'</code> because of the local scope of the function <code>f</code> that creates its own <a href="https://blog.finxter.com/python-namespaces-made-simple/" data-type="post" data-id="3460" target="_blank" rel="noreferrer noopener">namespace</a> with its own <code>old_variable</code> that overshadows the global <code>old_variable</code>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="6,11" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">old_variable = 'hello world'
new_string = 'hello finxter' def f(): # Replace old_old variable with new string 'hello finxter' exec(f'old_variable = "{new_string}"') f() print(old_variable)
# hello world
</pre>
<p class="has-global-color-8-background-color has-background">To overwrite a global variable within the <code>exec()</code> function, use the <code>global</code> keyword, followed by an empty space, the name of the global variable, a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-semicolons-how-they-work-and-why-haters-tell-you-to-avoid-them/" data-type="post" data-id="12600" target="_blank">semicolon</a> <code>;</code> to close the statement, and the expression to overwrite the global variable like so: <code>exec(f'global old_variable; old_variable = "{new_string}"')</code></p>
<p>Here’s the full example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="6,12" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">old_variable = 'hello world'
new_string = 'hello finxter' def f(): # Replace old_old variable with new string 'hello finxter' exec(f'global old_variable; old_variable = "{new_string}"') f() print(old_variable)
# hello finxter
</pre>
<p><strong>Related tutorial:</strong></p>
<ul>
<li><a href="https://blog.finxter.com/how-to-use-global-variables-in-a-python-function/" data-type="post" data-id="14662" target="_blank" rel="noreferrer noopener">How to Use Global Variables In a Python Function?</a></li>
</ul>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How to Use Global Variables Inside a Python Function?" width="780" height="439" src="https://www.youtube.com/embed/v2oLM6tDj04?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<h2>Method 4: Redirect Standard Output</h2>
<p><em>Okay, let’s do something crazy, shall we?</em> <img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f92f.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>
<p>Let’s redirect the standard output and print directly to the variable!</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" width="498" height="300" src="https://blog.finxter.com/wp-content/uploads/2022/05/ExplodindoBoomExplosaoCabecaexplodindoGIF.gif" alt="" class="wp-image-370256"/></figure>
</div>
<p>This method assumes you have a <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank">print()</a></code> statement within the expression passed into the <code>exec()</code> function such as shown in the following three examples:</p>
<ul>
<li><code>exec('print(2+2)')</code></li>
<li><code>exec('print([1, 2, 3, 4] + [5, 6])')</code></li>
<li><code>exec('print(2+2*0)')</code></li>
</ul>
<p>To get the output and store it in a variable <code>my_result</code>, you need to temporarily <a href="https://blog.finxter.com/7-easy-steps-to-redirect-your-standard-output-to-a-variable-python/" data-type="post" data-id="365385" target="_blank" rel="noreferrer noopener">redirect the standard output</a> to the variable. </p>
<p>The following code shows you how to accomplish exactly this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="15-16" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Step 1: Import libraries StringIO and sys
from io import StringIO
import sys # Step 2: Keep stdout in temporary variable
tmp = sys.stdout # Step 3: Capture standard output using a StringIO object
my_result = StringIO() # Step 4: Assign Standard Output Stream to StringIO object
sys.stdout = my_result # Step 5: Print to the standard output
expression = 'print(2+2)' # any exec() expression here
exec(expression) # Step 6: Clean up by redirecting stdout to Python shell
sys.stdout = tmp # Step 7: Get and print the string from stdout
print('VARIABLE:', my_result.getvalue())
# VARIABLE: 4
</pre>
<p>If you need some assistance understanding this whole idea of redirecting the standard output, have a look at our in-depth guide on the Finxter blog.</p>
<p class="has-global-color-8-background-color has-background"><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;" /> <strong>Related Article:</strong> <a href="https://blog.finxter.com/7-easy-steps-to-redirect-your-standard-output-to-a-variable-python/" data-type="post" data-id="365385">7 Easy Steps to Redirect Your Standard Output to a Variable (Python)</a></p>
<p>Note that this approach even works if you don’t have a <code>print()</code> statement in the original <code>exec()</code> expression because you can always artificially add the <code>print()</code> statement around the original expression like so:</p>
<ul>
<li><code>exec('2+2')</code> becomes <code>exec('print(2+2)')</code></li>
<li><code>exec('2+2*0')</code> becomes <code>exec('print(2+2*0)')</code></li>
<li><code>exec('[1, 2, 3] + [4, 5]')</code> becomes <code>exec('print([1, 2, 3] + [4, 5])')</code></li>
</ul>
<p>Even if it’s a bit clunky, after applying this short trick, you can redirect the standard output and store the result of <strong><em>any</em></strong> <code>exec()</code> expression in a variable.</p>
<p class="has-global-color-8-background-color has-background"><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;" /> <strong>Related Article:</strong> <a href="https://blog.finxter.com/how-to-assign-the-result-of-eval-to-a-python-variable/" data-type="URL" data-id="https://blog.finxter.com/how-to-assign-the-result-of-eval-to-a-python-variable/" target="_blank" rel="noreferrer noopener">How to Assign the Result of eval() to a Python Variable?</a></p>
<h2>Where to Go From Here?</h2>
<p>Enough theory. Let’s get some practice!</p>
<p>Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. </p>
<p>To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>You build high-value coding skills by working on practical coding projects!</strong></p>
<p>Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?</p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f680.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> If your answer is <strong><em>YES!</em></strong>, consider becoming a <a rel="noreferrer noopener" href="https://blog.finxter.com/become-python-freelancer-course/" data-type="page" data-id="2072" target="_blank">Python freelance developer</a>! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>If you just want to learn about the freelancing opportunity, feel free to watch my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and learn how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</div>


https://www.sickgaming.net/blog/2022/05/16/how-to-assign-the-result-of-exec-to-a-python-variable/