0

I am executing a Python (2.6.6) command directly from bash, like this :

bash-4.1$ python -c "for i in range(4) : print('a')"

which outputs

a
a
a
a

However, when I add something before the for loop, I get a SyntaxError:

bash-4.1$ python -c "myChar = 'a'; for i in range(4) : print(myChar)"
  File "<string>", line 1
    myChar = 'a'; for i in range(4) : print(myChar)
                    ^
SyntaxError: invalid syntax

no matter what I put before the semicolon. However,

bash-4.1$ python -c "i = 1; print i"

works just fine.

Any idea of what's happening here?

kojiro
  • 74,557
  • 19
  • 143
  • 201
P. Camilleri
  • 12,664
  • 7
  • 41
  • 76
  • Python has significant whitespace, and you cannot put arbitrary statements next to each other using `;`. It's like asking why a C snippet fails to work if you replace some of the curly braces with semicolons. – 9000 Jun 09 '15 at 14:47
  • 3
    To get your command to work you can do something like this `python -c $'myChar=\'a\'\nfor i in range(4): print(myChar)'` – Songy Jun 09 '15 at 14:47
  • @Songy Phew, that's ugly. –  Jun 09 '15 at 14:50
  • Hell yeah, but it gets the job done ;P – Songy Jun 09 '15 at 14:50
  • Getting "the job done" using ugly is not in the [Zen of Python](https://www.python.org/dev/peps/pep-0020/): "Beautiful is better than ugly." –  Jun 09 '15 at 14:51
  • :( `python -c $'myChar="b"\nfor i in range(4): print(myChar)'` I could remove some of the escaping for you. How's the Zen now? :D – Songy Jun 09 '15 at 14:52
  • @Songy: bash strings can include return characters, so there is no need to go to heroic lengths to include escaped newlines. `python -c "mychar='a'for i in range(4): print(myChar)' will work just fine. – rici Jun 09 '15 at 17:00

1 Answers1

2

Use a here document if you want to write Python code in a shell script.

$ python3.4 <<EOF
myChar = 'a'
for i in range(4):
    print(myChar)
EOF 

Output:

a
a
a
a

Read PEP 0008 and PEP 0020 about Python style.

  • 1
    That's a "here doc", not a "here string". A here string would be `python <<<"..."`, but you don't need that either. Just use a regular string with newline characters inside: `python -c "mychar = 'a'for i ... "`. Here docs (not here strings or direct strings) have the advantage of not needing to escape quotes, etc., but you normally want to disable variable expansion by using `<<"EOF"` – rici Jun 09 '15 at 17:09