Python one-liner 的语法错误 [英] Syntax error with Python one-liner

查看:33
本文介绍了Python one-liner 的语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

有效,并且

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

有效,但是

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

失败

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

为什么?

编辑我的解决方法:

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

(幸运的是它也适用于我的真实代码.)

(Luckily it worked for my real code too.)

推荐答案

只能使用 ; 将非复合语句分隔在一行上;语法不允许非复合语句和以分号分隔的复合语句.

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.

相关语法规则如下:

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

;simple_stmt 产生式中是唯一允许分号分隔语句的地方.有关更多详细信息,请参阅完整的 Python 语法.

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.

这篇关于Python one-liner 的语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆