Syntax error with Python one-liner

泄露秘密 提交于 2020-01-09 10:42:06

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/23730644/syntax-error-with-python-one-liner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!