2

On the command line,

python -c "z = [i for i in range(5)]; print (z)" gives

[0, 1, 2, 3, 4]

where ; means there should be a newline.

But what about a newline followed by a tab? Or (gasp) two tabs?

The following code is nonfunctional, but it illustrates what I'd like to be able to do:

python -c "z = [i for i in range(5)]; for i in z: print (i)"

and get as output:

1
2
3
4
5

So basically the question is: How do I execute the following code using python -c?

z = [i for i in range(5)] 
for i in z:
    print (i)
Ryan
  • 3,555
  • 1
  • 22
  • 36
  • If you use all in a string, you might use "\n" as a new line and add the correct number of spaces. – mrbTT May 06 '20 at 13:40
  • Please clarify your question. A multi-line program is a perfectly valid input for ``python -c``. Do you know how to write multi-line strings in your shell? – MisterMiyagi May 06 '20 at 13:51
  • @pfabri yes the answer by SilentGhost worked, but not the accepted answer, thank you! – Ryan May 06 '20 at 13:54

1 Answers1

4

Note that ; is not always a valid substitute for a newline, so the question is really: how do I supply arbitrary code. This basically depends on knowing how to use your shell.

In bash, you can construct true one-liners using $'...' quoting:

python -c $'z = [i for i in range(5)]\nfor i in z:\n    print(i)'

though it is easier to read if you can embed newlines yourself:

python -c '
z = [i for i in range(5)]
for i in z:
    print(i)
'

Note that since indentation is so significant, you can't easily do this if the call to python itself is indented in a shell script, as your script indentation would be part of the argument itself.

if [[ cmd = "do it" ]]; then

    # The Python script has to be dedented
    python -c '
z = [i for i in range(5)]
for i in z:
    print(i)
'
fi
chepner
  • 497,756
  • 71
  • 530
  • 681