Explain Codes LogoExplain Codes Logo

Executing multi-line statements in the one-line command-line

python
prompt-engineering
best-practices
functions
Nikita BarsukovbyNikita Barsukov·Jan 18, 2025
TLDR

You can execute multi-line Python statements in a single line using a semicolon ; :

for i in range(3): print(f'Number: {i}, Square: {i**2}'); # The semicolon is our friend 😉

If your script is stretched over multiple lines, use triple quotes inside an exec() call:

python -c "exec(\"\"\"for i in range(3):\n print(f'Number: {i}, Square: {i**2}')\"\"\")"

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():

python -c $'for i in range(3):\n print(f"Number: {i}, Square: {i**2}")' # semi-colon gets a break 🙌

Feeling adventurous? Try heredocs for larger scripts, but beware of their caveats:

python <<'EOF' import sys for i in range(int(sys.argv[1])): print(f'Count: {i}') # EOF, not the end of the world! EOF

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:

python -c "import sys; print(f'Hello, {sys.argv[1]}!')" YourName # Got your name right? 🤔

3. POSIX compliance

If you're after POSIX compliance, a printf command substitution or a pipeline to Python's stdin is your destination:

printf "print('Adventurous POSIX journey')" | python # 🚀 Taking off...

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:

python -c "print(*(f'Count: {i}' for i in range(5)), sep='\n')" # Nimble Number Ninjas

For output, consider sys.stdout.write instead of print, and to fire inline functions, map() with lambda is your weapon:

python -c "import sys; map(lambda x: sys.stdout.write(f'{x}\n'), range(5))"

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.