08-05-2020, 09:18 AM
How to Execute Multiple Lines in a Single Line Python From Command-Line?
Summary: To make a Python one-liner out of any multi-line Python script, replace the new lines with a new line character and pass the result into the function. You can run this script from the outside (command line, shell, terminal) by using the command .
Problem: Given a multi-line code script in Python. How to execute this multi-line script in a single line of Python code? How to do it from the command line?
Example: Say, you have the following for loopwith a nested if statement in the for loop body. You want to run this in a single line from your command line?
The code prints five numbers to the shell. It only prints the odd values of. If takes an even value, it prints the loop variable .
Let’s have a look at the three methods to solve this problem!
Method 1: exec()
You can write any source code into a string and run the string using the built-in function in Python. This is little known—yet, hackersoften use this to pack malicious code into a single line that’s seemingly harmless.
If you have code that spans multiple lines, you can pack it into a single-line string by using the newline character in your string:
This one-liner code snippet is semantically equivalent to the above nested for loop that requires seven lines of code! The output is the same:
Try it yourself in our interactive code shell:
https://repl.it/@finxter/YellowishGrowli...?lite=true
Exercise: Remove the else branch of this code. What’s the output? Run the code to check if you were right!
Method 2: From Command-Line | python -c + exec()
Of course, you can also run this code from your Win/Linux/Mac command line or shell.
![[Image: image-33.png]](https://blog.finxter.com/wp-content/uploads/2020/07/image-33.png)
Just make sure to use the prefix and then pack the single-line multi-liner into a string value that is passed as an argument to the program.
This is how it looks in my Win 10 powershell:
Method 3: Use Ternary Operator to One-Linerize the Code
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 “Python One-Liners” from NoStarch)!
In this code, you use the ternary operator:
You can easily convince yourself that the code does the same thing in a single line!
Python One-Liners Book
Python programmers will improve their computer science skills with these useful one-liners.
![[Image: 3D_cover-1024x944.jpg]](https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg)
Python One-Linerswill 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.
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:
• Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
• Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
• Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
• 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
• Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
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.
Get your Python One-Liners Now!!
Summary: 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:
exec(...)Code:
python -c "exec(...)"Problem: Given a multi-line code script in Python. How to execute this multi-line script in a single line of Python code? How to do it from the command line?
Example: Say, you have the following for loopwith a nested if statement in the for loop body. You want to run this in a single line from your command line?
Code:
x = 10
for i in range(5): if x%2 == 0: print(i) else: print(x) x = x - 1 '''
0
9
2
7
4 '''The code prints five numbers to the shell. It only prints the odd values of
Code:
xCode:
xCode:
iLet’s have a look at the three methods to solve this problem!
Method 1: exec()
You can write any source code into a string and run the string using the built-in
Code:
exec()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:
# 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')This one-liner code snippet is semantically equivalent to the above nested for loop that requires seven lines of code! The output is the same:
Code:
'''
0
9
2
7
4 '''Try it yourself in our interactive code shell:
https://repl.it/@finxter/YellowishGrowli...?lite=true
Exercise: Remove the else branch of this code. What’s the output? Run the code to check if you were right!
Method 2: From Command-Line | python -c + exec()
Of course, you can also run this code from your Win/Linux/Mac command line or shell.
![[Image: image-33.png]](https://blog.finxter.com/wp-content/uploads/2020/07/image-33.png)
Just make sure to use the
Code:
python -cCode:
pythonThis is how it looks in my Win 10 powershell:
Code:
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
4Of 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 “Python One-Liners” from NoStarch)!
In this code, you use the ternary operator:
Code:
# Method 3
for i in range(5): print(10-i) if i%2 else print(i)You can easily convince yourself that the code does the same thing in a single line!
Python One-Liners Book
Python programmers will improve their computer science skills with these useful one-liners.
![[Image: 3D_cover-1024x944.jpg]](https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg)
Python One-Linerswill 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.
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:
• Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
• Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
• Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
• 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
• Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
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.
Get your Python One-Liners Now!!

