Sick Gaming
[Tut] How to Execute Multiple Lines in a Single Line Python From Command-Line? - 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 Execute Multiple Lines in a Single Line Python From Command-Line? (/thread-96565.html)



[Tut] How to Execute Multiple Lines in a Single Line Python From Command-Line? - xSicKxBot - 08-05-2020

How to Execute Multiple Lines in a Single Line Python From Command-Line?

<div><p class="has-pale-cyan-blue-background-color has-background"><strong>Summary</strong>: To make a Python one-liner out of any multi-line Python script, replace the new lines with a new line character <code>'\n'</code> and pass the result into the <code>exec(...)</code> function. You can run this script from the outside (command line, shell, terminal) by using the command <code>python -c "exec(...)"</code>. </p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="[Don't Do This At Home] How To One-Linerize Every Multi-Line Python Script &amp; Run It From The Shell" width="1400" height="788" src="https://www.youtube.com/embed/zGJgctQEkSU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p><strong>Problem</strong>: Given a multi-line code script in Python. How to execute this multi-line script in a <a href="https://blog.finxter.com/python-one-line-x/" target="_blank" rel="noreferrer noopener" title="Python One Line X">single line of Python code</a>? How to do it from the command line?</p>
<p><strong>Example</strong>: Say, you have the following for <a href="https://blog.finxter.com/python-loops/" target="_blank" rel="noreferrer noopener" title="Python Loops">loop </a>with a nested if statement in the for loop body. You want to run this in a single line from your command line?</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="">x = 10
for i in range(5): if x%2 == 0: print(i) else: print(x) x = x - 1 '''
0
9
2
7
4 '''</pre>
<p>The code prints five numbers to the shell. It only prints the odd values of <code>x</code>. If <code>x</code> takes an even value, it prints the loop variable <code>i</code>. </p>
<p>Let’s have a look at the three methods to solve this problem!</p>
<h2>Method 1: exec()</h2>
<p>You can write any source code into a string and run the string using the built-in <code>exec()</code> function in Python. This is little known—yet, <a href="https://blog.finxter.com/define-a-function-in-one-line/" target="_blank" rel="noreferrer noopener" title="3 (Not So) Pythonic Ways to Define a Function in One Line [for Hackers]">hackers </a>often use this to pack malicious code into a single line that’s seemingly harmless. </p>
<p>If you have code that spans multiple lines, you can pack it into a single-line string by using the newline character <code>'\n'</code> in your string:</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=""># Method 1
exec('x = 10\nfor i in range(5):\n if x%2 ==0: print(i)\n else: print(x)\n x = x-1')
</pre>
<p>This one-liner code snippet is semantically equivalent to the above nested <a href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/" target="_blank" rel="noreferrer noopener" title="Python One Line For Loop [A Simple Tutorial]">for loop</a> that requires seven lines of code! The output is the same:</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="">'''
0
9
2
7
4 '''</pre>
<p>Try it yourself in our interactive code shell:</p>
<p> <iframe height="400px" width="100%" src="https://repl.it/@finxter/YellowishGrowlingMonotone?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe> </p>
<p><em><strong>Exercise</strong>: Remove the else branch of this code. What’s the output? Run the code to check if you were right!</em></p>
<h2>Method 2: From Command-Line | python -c + exec()</h2>
<p>Of course, you can also run this code from your Win/Linux/Mac command line or shell.</p>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/07/image-33.png" alt="" class="wp-image-11525" srcset="https://blog.finxter.com/wp-content/uploads/2020/07/image-33.png 1005w, https://blog.finxter.com/wp-content/uploads/2020/07/image-33-300x32.png 300w, https://blog.finxter.com/wp-content/uploads/2020/07/image-33-768x82.png 768w, https://blog.finxter.com/wp-content/uploads/2020/07/image-33-150x16.png 150w" sizes="(max-width: 1005px) 100vw, 1005px" /></figure>
<p>Just make sure to use the <code>python -c</code> prefix and then pack the single-line multi-liner into a string value that is passed as an argument to the <code>python</code> program.</p>
<p>This is how it looks in my Win 10 powershell:</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="">PS C:\Users\xcent> python -c "exec('x = 10\nfor i in range(5):\n if x%2 ==0: print(i)\n else: print(x)\n x = x-1')"
0
9
2
7
4</pre>
<h2>Method 3: Use Ternary Operator to One-Linerize the Code</h2>
<p>Of course, you can also create your own semantically-equivalent one-liner using a bit of creativity and Python One-Liner skills (e.g., acquired through reading my book <a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE">“Python One-Liners”</a> from NoStarch)!</p>
<p>In this code, you use the <a href="https://blog.finxter.com/python-one-line-ternary/" target="_blank" rel="noreferrer noopener" title="Python One Line Ternary">ternary operator</a>:</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=""># Method 3
for i in range(5): print(10-i) if i%2 else print(i)</pre>
<p>You can easily convince yourself that the code does the same thing in a single line!</p>
<h2>Python One-Liners Book</h2>
<p><strong>Python programmers will improve their computer science skills with these useful one-liners.</strong></p>
<figure class="wp-block-image size-medium is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noopener noreferrer"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg" alt="Python One-Liners" class="wp-image-10007" width="512" height="472" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-300x277.jpg 300w, https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-768x708.jpg 768w" sizes="(max-width: 512px) 100vw, 512px" /></a></figure>
<p><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Python One-Liners</em> </a>will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.</p>
<p>The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:</p>
<p><strong>•</strong>&nbsp;&nbsp;Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution<br /><strong>•</strong>&nbsp;&nbsp;Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics<br /><strong>•</strong>&nbsp;&nbsp;Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning<br /><strong>•</strong>&nbsp;&nbsp;Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators<br /><strong>•</strong>&nbsp;&nbsp;Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting</p>
<p>By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.</p>
<p><strong><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Get your Python One-Liners Now!!</em></a></strong></p>
</div>


https://www.sickgaming.net/blog/2020/07/29/how-to-execute-multiple-lines-in-a-single-line-python-from-command-line/