Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to execute Python multi-line statements in the one-line at command-line?
There are multiple ways to execute Python multi-line statements in a single command-line call. You can use bash's multi-line support or compress statements using newline characters.
Using Bash Multi-line Support
Bash supports multi-line statements, which you can use with the python -c command ?
$ python -c '
> a = True
> if a:
> print("a is true")
> '
The output of the above command is ?
a is true
Using Newline Characters in Single Line
If you prefer to have the Python statement in a single line, you can use the \n newline character between commands ?
$ python -c $'a = True\nif a: print("a is true")'
The output of the above command is ?
a is true
Using Semicolons for Simple Statements
For simple statements that don't require proper indentation, you can use semicolons to separate commands ?
$ python -c "x = 10; y = 20; print(f'Sum is {x + y}')"
The output of the above command is ?
Sum is 30
Complex Example with Functions
You can also define and call functions using newline characters ?
$ python -c $'def greet(name):\n return f"Hello, {name}"\nprint(greet("World"))'
The output of the above command is ?
Hello, World
Conclusion
Use bash multi-line support for readable code or \n characters for compact one-liners. Choose the method that best fits your command-line workflow and code complexity.
