Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax error with Python one-liner

python -c 'import sys; print "a"'

works, and

python -c 'for a in [1, 2, 3]: print a'

works, but

python -c 'import sys; for a in [1, 2, 3]: print a'

fails with

File "<string>", line 1
  import sys; for a in [1, 2, 3]: print a
                ^

Why?


EDIT My workaround:

python -c 'import sys; print "\n".join([1, 2, 3])'

(Luckily it worked for my real code too.)

like image 410
Paul Draper Avatar asked May 19 '14 06:05

Paul Draper


People also ask

What is an example of a syntax error in Python?

Here are some examples of syntax errors in Python: myfunction(x, y): return x + y else: print("Hello!") if mark >= 50 print("You passed!") if arriving: print("Hi!") esle: print("Bye!") if flag: print("Flag is set!")

Why does Python say += is invalid?

x += 1 is an augmented assignment statement in Python. You cannot use statements inside the print statement , that is why you get the syntax error.


2 Answers

You can only use ; to separate non-compound statements on a single line; the grammar makes no allowance for a non-compound statement and a compound statement separated by a semicolon.

The relevant grammar rules are as follows:

stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE

The ; in the simple_stmt production is the only place where semicolons are allowed to separate statements. For further details, see the full Python grammar.

like image 83
user2357112 supports Monica Avatar answered Sep 19 '22 06:09

user2357112 supports Monica


Not an answer to your exact question, but still may help someone. You can actually split the command line in shell.

sh/bash/etc:

python -c 'import sys
for a in [1, 2, 3]: print a'

Windows cmd (C:\> and 'More?' are cmd prompts, don't enter those):

C:\>python -c import sys^
More?
More? for a in [1, 2, 3]: print a

Added in 2021: For some reason the cmd version above does not work on my current Windows 10 environment. Seems like w/o quotes Python interpreter truncates the command at first space. This variant still works:

C:\>python -c ^
More? "import sys^
More? 
More? for a in [1, 2, 3]: print a

Please note, that you need to press ENTER immediately after the caret (^) symbol. Also please note the double quote on the first continuation line in the last example.

like image 34
Alex Che Avatar answered Sep 19 '22 06:09

Alex Che