A problem with for loops in Python one-liners

A problem with for loops in one-liners

A DevOps friend of mine came up with this problem. The following script works without a problem:

#!/usr/bin/env python3

import os

for k, v in os.environ.items():
    print(f'{k}={v}')

When you try to do the same thing with a one-liner on the shell, using the -c option to python, it fails:

python -c "import os; for k, v in os.environ.items(): print(f'{k}={v}')"

You get an error about invalid syntax:

$ python -c "import os;for k, v in {'a': 'b'}.items(): print(k, v)"
  File "<string>", line 1
    import os;for k, v in {'a': 'b'}.items(): print(k, v)
                ^
SyntaxError: invalid syntax

Why is that? Some googling brings up a thread on stackoverflow. There it says the problem is the for loop.[1] You’re not allowed to have anything in front of a loop line in Python.

What to do? List comprehensions to the rescue:

python3 -c "import os; [print(f'{k}={v}') for k, v in os.environ.items()]"

This avoids the loop and everything is fine.

And why would you want to have that command on one line? Because the command had to be passed to a Docker container for build or run (I don’t remember which) and you can’t pass multiline code in that scenario.[2] So the whole command must be on a single line.


2. And, most probably, passing multiline Python code that’s properly indented is even more tricky.

links

social