{"id":116295,"date":"2020-07-29T11:53:45","date_gmt":"2020-07-29T11:53:45","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=11519"},"modified":"2020-07-29T11:53:45","modified_gmt":"2020-07-29T11:53:45","slug":"how-to-execute-multiple-lines-in-a-single-line-python-from-command-line","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/07\/29\/how-to-execute-multiple-lines-in-a-single-line-python-from-command-line\/","title":{"rendered":"How to Execute Multiple Lines in a Single Line Python From Command-Line?"},"content":{"rendered":"<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>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" title=\"[Don&#039;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>\n<\/div>\n<\/figure>\n<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>\n<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>\n<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\nfor i in range(5): if x%2 == 0: print(i) else: print(x) x = x - 1 '''\n0\n9\n2\n7\n4 '''<\/pre>\n<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>\n<p>Let&#8217;s have a look at the three methods to solve this problem!<\/p>\n<h2>Method 1: exec()<\/h2>\n<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&#8212;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&#8217;s seemingly harmless. <\/p>\n<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>\n<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\nexec('x = 10\\nfor i in range(5):\\n if x%2 ==0: print(i)\\n else: print(x)\\n x = x-1')\n<\/pre>\n<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>\n<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=\"\">'''\n0\n9\n2\n7\n4 '''<\/pre>\n<p>Try it yourself in our interactive code shell:<\/p>\n<p> <iframe loading=\"lazy\" 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>\n<p><em><strong>Exercise<\/strong>: Remove the else branch of this code. What&#8217;s the output? Run the code to check if you were right!<\/em><\/p>\n<h2>Method 2: From Command-Line | python -c + exec()<\/h2>\n<p>Of course, you can also run this code from your Win\/Linux\/Mac command line or shell.<\/p>\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" 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>\n<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>\n<p>This is how it looks in my Win 10 powershell:<\/p>\n<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')\"\n0\n9\n2\n7\n4<\/pre>\n<h2>Method 3: Use Ternary Operator to One-Linerize the Code<\/h2>\n<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\">&#8220;Python One-Liners&#8221;<\/a> from NoStarch)!<\/p>\n<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>\n<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\nfor i in range(5): print(10-i) if i%2 else print(i)<\/pre>\n<p>You can easily convince yourself that the code does the same thing in a single line!<\/p>\n<h2>Python One-Liners Book<\/h2>\n<p><strong>Python programmers will improve their computer science skills with these useful one-liners.<\/strong><\/p>\n<figure class=\"wp-block-image size-medium is-resized\"><a href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noopener noreferrer\"><img loading=\"lazy\" decoding=\"async\" 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=\"auto, (max-width: 512px) 100vw, 512px\" \/><\/a><\/figure>\n<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 &#8220;one-liners&#8221;: concise statements of useful functionality packed into a single line of code. You&#8217;ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.<\/p>\n<p>The book&#8217;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&#8217;ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You&#8217;ll also learn how to:<\/p>\n<p><strong>\u2022<\/strong>&nbsp;&nbsp;Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning<br \/><strong>\u2022<\/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>\u2022<\/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>\n<p>By the end of the book, you&#8217;ll know how to write Python at its most refined, and create concise, beautiful pieces of &#8220;Python art&#8221; in merely a single line.<\/p>\n<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>\n","protected":false},"excerpt":{"rendered":"<p>Summary: To make a Python one-liner out of any multi-line Python script, replace the new lines with a new line character &#8216;\\n&#8217; and pass the result into the exec(&#8230;) function. You can run this script from the outside (command line, shell, terminal) by using the command python -c &#8220;exec(&#8230;)&#8221;. Problem: Given a multi-line code script [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-116295","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/116295","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=116295"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/116295\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=116295"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=116295"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=116295"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}