Executing multi-line statements in the one-line command-line
You can execute multi-line Python statements in a single line using a semicolon ;
:
If your script is stretched over multiple lines, use triple quotes inside an exec()
call:
While semicolons let you squeeze simple statements into one line, exec()
with triple quotes handles "heavy-lifters" like larger scripts with newlines.
Strategizing complex one-liners
1. In bash, we trust
Give ANSI C-Quoted strings a try ($'...'
) to represent newlines, making it possible to split Python statements without explicit exec()
:
Feeling adventurous? Try heredocs for larger scripts, but beware of their caveats:
Remember, 'EOF' needs those quotes to avoid shell variable expansion and escape embedded quotes when called for duty.
2. Interaction modes
Get interactive with input()
or use sys.argv
for handily access shell-variable values:
3. POSIX compliance
If you're after POSIX compliance, a printf command substitution or a pipeline to Python's stdin is your destination:
4.Cryptic is not always cool
For complex tasks, “with great power comes great responsibility.” Don’t obscure your code; sometimes, creating a small .py
file can help:
For output, consider sys.stdout.write
instead of print, and to fire inline functions, map()
with lambda
is your weapon:
Remember though, in the kingdom of one-liners, readability is king. Don’t replace loops with map
at the cost of clarity!
Trouble in paradise
Even one-liners have their problems. Here are some common pitfalls to avoid:
1. Indentation woes and tricky tabs
In Python, incorrect indentation or hard tabs can lead to IndentationErrors. Remove leading TAB characters in command-line usages.
2. Heredoc gotchas
Ensure your heredoc marker word doesn't appear within the document text, and escape single quotes when needed. Check the bash man page for complete information on heredocs.
Was this article helpful?