16
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.)

5
  • What OS and what shell are you using? Commented May 19, 2014 at 6:11
  • I can reproduce it ubuntu+bash, python 2.7.3. Commented May 19, 2014 at 6:12
  • It's not connected to the shell or the -c flag; the same thing happens in the REPL. Commented May 19, 2014 at 6:14
  • You're missing a line in the error message: SyntaxError: invalid syntax Commented Dec 13, 2018 at 18:35
  • 1
    Another workaround for Python 3, use a comprehension: python -c 'import sys; [print(i) for i in [1, 2, 3]] Commented Dec 31, 2018 at 14:35

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.